表单不响应 KeyDown 事件 [英] Forms not responding to KeyDown events

查看:26
本文介绍了表单不响应 KeyDown 事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在我的 Windows 窗体项目上工作了一段时间,我决定尝试使用键盘快捷键.经过一些阅读,我想我只需要编写一个事件处理程序并将其绑定到表单的 KeyDown 事件:

I've been working for a while on my Windows Forms project, and I decided to experiment with keyboard shortcuts. After a bit of reading, I figured I had to just write an event handler and bind it to the form's KeyDown event:

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Control && e.Alt && e.KeyCode == Keys.O)
    {
        MessageBox.Show("Ctrl+Alt+O: magic!");
    }
}

我采用了打开 Visual Studio 设计器的属性"面板的好方法,然后双击表单的 KeyDown 事件以生成 Form1_KeyDown 事件处理程序.但是在测试我的应用程序时,表单根本不响应 Ctrl+Alt+O 键盘快捷键.Visual Studio 设计器确实生成了将事件处理程序绑定到表单的代码:

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() 调用以检查它是否被调用,但也没有运气.

So I tried adding a Console.WriteLine() call to the handler to check that it was being called at all, but no luck on that either.

此外,我尝试在事件绑定调用(如上所示)上设置断点,发现程序到达该断点就好了.但是我在方法定义本身中设置的任何断点都没有达到.

Also, I tried to set a breakpoint on the event binding call (shown just above) and found that the program reaches that breakpoint just fine. But any breakpoints I set within the method definition itself are never reached.

为了确保我正确地执行了前几步,我尝试重复它们:

To make sure I was doing the first few steps correctly, I tried repeating them with:

  • 同一解决方案中的新表单.
    同样的问题:当我按下 Ctrl+Alt+O 键盘快捷键时表单没有响应,并且调试器没有响应甚至进入事件处理程序. 再次尝试,它可以工作.

  • 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 事件?

So I'm quite lost here. What's preventing all the forms in this one project from receiving KeyDown events?

推荐答案

您的表单是否将 KeyPreview 属性设置为 true?

Does your form have KeyPreview property set to true?

Form.KeyPreview 属性

获取或设置一个值,该值指示表单是否将接收密钥事件传递给具有焦点的控件之前的事件.

Gets or sets a value indicating whether the form will receive key events before the event is passed to the control that has focus.

http://msdn.microsoft.com/en-us/library/system.windows.forms.form.keypreview.aspx

这篇关于表单不响应 KeyDown 事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆