How can I capture keys on a WinForms application when the application is in focus?

.net, c#, winforms

Solution

Set `KeyPreview` to true

Here's a sample `OnKeyDown` override for your form that eats the keystroke and prevents it from being propagated to other events:

protected override void OnKeyDown(KeyEventArgs e)
{
    e.SuppressKeyPress = true; // do this to 'eat' the keystroke
    base.OnKeyDown(e);
}

Problem

How can I capture keys on a WinForms application when the application is in focus? I have tried using the `Form_KeyDown` and `Form_KeyUp` events but they don't work the way I want them to.

Original source