Capture combination key event in a Windows Forms application

In case you want to use multiple modifiers KeyEventArgs also has boolean values to indicate if CTRL, ALT or SHIFT is pressed.

Example:

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Control && e.Alt && e.Shift && e.KeyCode == Keys.F12)
        MessageBox.Show("My message");
}

In this example the messagebox is show if CTRL, ALT, SHIFT and F12 are pressed at the same time.


Handle the KeyDown event and have something like:

if (e.Modifiers == Keys.Shift && e.KeyCode == Keys.Up)
{
    MessageBox.Show("My message");
}

The event handler has to be on the Main Form and you need to set the KeyPreview property to true. This can be done in design mode from the properties dialog.

Tags:

C#

Winforms