Fire Form KeyPress事件

Jav*_*ram 6 .net c# events keyevent winforms

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

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

我曾尝试this.Focus();FormLoad()事件,但仍然KeyPress事件不工作.

Cod*_*ray 10

您需要覆盖表单的ProcessCmdKey方法.这是您通知子控件具有键盘焦点时发生的关键事件的唯一方式.

示例代码:

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);
}
Run Code Online (Sandbox Code Playgroud)

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

  • 请注意,ProcessCmdKey()不是*替代KeyPress.虚拟键和它们被翻译成的字符之间存在很大差异.没有什么好方法可以获得相当于KeyPress的功能. (3认同)

Joh*_*ner 5

尝试将 Form 的KeyPreview属性设置为 True。