那麼,你可能不得不使用這個有點冒險的解決方案。整個想法是你必須按按住Alt鍵碼。我試過用MouseDown
事件(即使在PreFilterMessage handler
),但它失敗了。唯一的事件是適合於在觸發時按住Alt鍵爲MouseEnter
。您必須爲所有ToolStripItems
註冊MouseEnter
事件處理程序,當鼠標離開其中一個項目時,必須在MouseLeave
事件處理程序中釋放Alt項。在替代鍵發佈後,我們必須發送ESC
鍵以使表單處於活動狀態(否則,即使在控制按鈕上,包括Minimize, Maximize, Close
在內,所有懸停效果似乎都被忽略)。下面是可用的代碼:
public partial class Form1 : Form {
[DllImport("user32.dll", SetLastError = true)]
static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo);
public Form1(){
InitializeComponent();
//Register event handlers for all the toolstripitems initially
foreach (ToolStripItem item in toolStrip1.Items){
item.MouseEnter += itemsMouseEnter;
item.MouseLeave += itemsMouseLeave;
}
//We have to do this if we add/remove some toolstripitem at runtime
//Otherwise we don't need the following code
toolStrip1.ItemAdded += (s,e) => {
item.MouseEnter += itemsMouseEnter;
item.MouseLeave += itemsMouseLeave;
};
toolStrip1.ItemRemoved += (s,e) => {
item.MouseEnter -= itemsMouseEnter;
item.MouseLeave -= itemsMouseLeave;
};
}
bool pressedAlt;
private void itemsMouseEnter(object sender, EventArgs e){
if (!pressedAlt) {
//Hold the Alt key
keybd_event(0x12, 0, 0, 0);//VK_ALT = 0x12
pressedAlt = true;
}
}
private void itemsMouseLeave(object sender, EventArgs e){
if (pressedAlt){
//Release the Alt key
keybd_event(0x12, 0, 2, 0);//flags = 2 -> Release the key
pressedAlt = false;
SendKeys.Send("ESC");//Do this to make the GUI active again
}
}
}