Acidic
Acidic

Reputation: 6280

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?

Upvotes: 2

Views: 1904

Answers (2)

João Angelo
João Angelo

Reputation: 57718

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.

Upvotes: 1

Ventsyslav Raikov
Ventsyslav Raikov

Reputation: 7202

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

Upvotes: 0

Related Questions