简体   繁体   English

C#-Windows窗体中的KeyDown事件问题

[英]C# - KeyDown Event Issue in Windows Form

When the main form loads, I am trying to set up a key event handler as follows: 加载主窗体时,我尝试按如下所示设置键事件处理程序:

private void FormMain_Load(object sender, EventArgs e)
{
    KeyDown += FormMain_KeyDown;
}

and the function that is called: 以及被称为的函数:

private void FormMain_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Escape)
    {
        // Do something.
    }
}

The problem is that the form doesn't react to Escape (or any other key I tried). 问题在于表单对Escape(或我尝试的任何其他键)没有反应。 And the funny thing is that a different form from the same project uses similar code without any issues. 有趣的是,与同一项目不同的表单使用相似的代码而没有任何问题。 Can anyone please tell me what I am doing wrong? 谁能告诉我我做错了吗?

There's a Property called KeyPreview on the form, you need to set it to true. 表单上有一个称为KeyPreview的属性,您需要将其设置为true。 Then on keypress your handler will fire, then any handler on the control that has focus will. 然后在按键时您的处理程序将触发,然后控件上具有焦点的任何处理程序将触发。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM