我已经在 Windows 窗体项目上工作了一段时间,并且决定尝试使用键盘快捷键。经过一番阅读后,我认为我必须编写一个事件处理程序并将其绑定到表单的 KeyDown 事件:
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.Alt && e.KeyCode == Keys.O)
{
MessageBox.Show("Ctrl+Alt+O: magic!");
}
}
I did that the good ol' way of opening the Properties panel of the Visual Studio designer, then double-clicking on the KeyDown event of my form to generate the Form1_KeyDown
event handler. But on testing my application, the form doesn't respond at all to the Ctrl+Alt+O keyboard shortcut. The Visual Studio designer did generate the code to bind the event handler to the form though:
private void InitializeComponent()
{
// ...
this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.Form1_KeyDown);
// ...
}
所以我尝试添加一个Console.WriteLine()
调用处理程序来检查它是否被调用,但也没有运气。
另外,我尝试在事件绑定调用上设置断点(如上所示),发现程序很好地到达了该断点。但是我在方法定义本身中设置的任何断点都永远不会到达。
为了确保我正确执行了前几个步骤,我尝试使用以下命令重复它们:
A new form in the same solution.
Same issue: the form doesn't respond when I press my Ctrl+Alt+O keyboard shortcut and the debugger isn't even stepping into the event handler. Tried this again and it works.
全新的 WinForms 解决方案。
它工作得很好:出现消息对话框(Console.WriteLine()
通话也有效)。
所以我在这里很迷路。是什么阻止了该项目中的所有表单接收 KeyDown 事件?
您的表单是否将 KeyPreview 属性设置为 true?
Form.KeyPreview 属性
获取或设置一个值,该值指示表单是否接收密钥
在事件传递给具有焦点的控件之前发生的事件。
http://msdn.microsoft.com/en-us/library/system.windows.forms.form.keypreview.aspx
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)