简体   繁体   中英

Overriding Windows Forms default behavior for some key events

I've created a Form with a simple game. 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.

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.

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. 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.

Override form's OnKeyDown method. And don't forget to call base.OnKeyDown at the end.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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