在我的应用程序中,我希望用户能够按住Alt以将某些修改应用于鼠标操作。就像使用鼠标滚轮而不是垂直滚动一样,视图将水平滚动(在Alt被按住时)。
这很好用,但是在 release 之后Alt,我的控件不再有焦点。当我按下Space时,我可以看到原因。窗口菜单获得了焦点,因为我按下了Alt。
我该如何防止这种情况发生?
Fixing this isn't so easy, you need to prevent the WM_SYSKEYDOWN message from reaching the default window procedure. That's only practical by filtering it before it reaches the control with the focus. That's possible by having your form implement the IMessageFilter interface. Like this:
public partial class Form1 : Form, IMessageFilter {
public Form1() {
InitializeComponent();
Application.AddMessageFilter(this);
}
protected override void OnFormClosed(FormClosedEventArgs e) {
Application.RemoveMessageFilter(this);
base.OnFormClosed(e);
}
public bool PreFilterMessage(ref Message m) {
// Trap WM_SYSKEYUPDOWN message for the ALT key
if ((Keys)m.WParam.ToInt32() == Keys.Menu) {
if (m.Msg == 0x104) { AltKeyPressed = true; return true; }
if (m.Msg == 0x105) { AltKeyPressed = false; return true; }
}
return false;
}
private bool AltKeyPressed;
}
Beware of the many side effects, it stops a menu behaving normally and shortcut keystrokes that use Alt are not going to work anymore. Do consider using Ctrl or Shift instead.
释放 Alt 手势后,通过调用 Control.Focus() 以编程方式强制您的控件具有焦点。
为什么这个黑客可以接受?因为此行为仅限于您的控件具有焦点且手势已成功处理时的实例。
我认为您需要在键盘事件上注册并将事件标记为已处理,
我的意思不是 KeyPressed 甚至 KeyDown ......我的意思是 OnPreviewKeyDown (不记得确切的名称,但谷歌搜索会做)