简体   繁体   English

覆盖某些关键事件的Windows Forms默认行为

[英]Overriding Windows Forms default behavior for some key events

I've created a Form with a simple game. 我用一个简单的游戏创建了一个Form The game requires input from the arrow keys, among others, but a few buttons I've placed on the form are stealing these key events. 游戏需要箭头键等的输入,但是我在窗体上放置的一些按钮正在窃取这些键事件。

From what I understand, this is the default behavior of any Windows Forms application, in order for the user to be able to change focus between the various controls. 据我了解,这是任何Windows Forms应用程序的默认行为,以便用户能够在各个控件之间更改焦点。

My question is, how do I get around that and make sure I can use the input from these keys? 我的问题是,如何解决这个问题并确保可以使用这些键的输入?

You can override the Form.ProcessCmdKey method in order to be able to handle every key press of the user. 您可以重写Form.ProcessCmdKey方法,以便能够处理用户的每次按键操作。

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    if (keyData == Keys.Down || keyData == Keys.Up)
    {
        // Process keys

        return true;
    }

    return base.ProcessCmdKey(ref msg, keyData);
}

Returning true signals that no further process should be executed and the default behavior of the key will not have any effect. 返回true信号表示不应再执行进一步的处理,并且键的默认行为不会有任何影响。 For example you'll no longer be able to move focus between controls using the TAB key, so you probably should only be returning true for key presses that are only handled by the game. 例如,您将不再能够使用TAB键在控件之间移动焦点,因此您可能应该只对仅由游戏处理的按键返回true。

Override form's OnKeyDown method. 重写窗体的OnKeyDown方法。 And don't forget to call base.OnKeyDown at the end. 并且不要忘了最后调用base.OnKeyDown。

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

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