好吧,您可能不得不使用这个有点hacky的解决方案。整个想法是您必须通过代码按住Alt键。我已经尝试过MouseDown
事件(即使在 a 中PreFilterMessage handler
),但它失败了。Alt唯一适合在触发时按住键的事件是MouseEnter
. 您必须MouseEnter
为所有的 注册事件处理程序ToolStripItems
,当鼠标离开这些项目之一时,您必须释放事件处理程序Alt中的键。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
}
}
}