Fire Form KeyPress 事件 [英] Fire Form KeyPress event

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

问题描述

我有一个 C# winform,上面有 1 个按钮.
现在,当我运行我的应用程序时,按钮会自动获得焦点.

I have a C# winform, on which I have 1 button.
Now, when I run my application, the button gets focus automatically.

问题是我的表单的 KeyPress 事件不起作用,因为按钮已聚焦.

The problem is KeyPress event of my form does not work because the button is focused.

我已经在 FormLoad() 事件上尝试了 this.Focus();,但 KeyPress 事件仍然不起作用.

I have tried this.Focus(); on FormLoad() event, but still the KeyPress event is not working.

推荐答案

您需要覆盖 ProcessCmdKey 方法 用于您的表单.这是您在子控件获得键盘焦点时收到关键事件通知的唯一方式.

You need to override the ProcessCmdKey method for your form. That's the only way you're going to be notified of key events that occur when child controls have the keyboard focus.

示例代码:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    // look for the expected key
    if (keyData == Keys.A)
    {
        // take some action
        MessageBox.Show("The A key was pressed");

        // eat the message to prevent it from being passed on
        return true;

        // (alternatively, return FALSE to allow the key event to be passed on)
    }

    // call the base class to handle other key events
    return base.ProcessCmdKey(ref msg, keyData);
}

至于为什么 this.Focus() 不起作用,那是因为表单本身无法获得焦点.特定的控件必须具有焦点,因此当您将焦点设置到表单时,它实际上将焦点设置到第一个可以接受具有最低 TabIndex 价值.在这种情况下,这是您的按钮.

As for why this.Focus() doesn't work, it's because a form can't have the focus by itself. A particular control has to have the focus, so when you set focus to the form, it actually sets the focus to the first control that can accept the focus that has the lowest TabIndex value. In this case, that's your button.

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

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