消防格式键preSS事件事件、格式、preSS

2023-09-02 10:41:26 作者:恸

我有一个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.

现在的问题是我的形式主要preSS 事件不会工作,因为该按钮被聚焦。

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

我已经试过 this.Focus(); FormLoad()事件,但仍然是关键preSS事件是行不通的。

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.

样品code:

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.