Joan Venge Joan Venge - 2 months ago 12
C# Question

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

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.

Answer

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);
}