17

When the user presses the Shift + UP keys, I want my form to respond by calling up a message box.

How do I do this in Windows Forms?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Graviton
  • 81,782
  • 146
  • 424
  • 602

3 Answers3

26

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.

Syed Farjad Zia Zaidi
  • 3,302
  • 4
  • 27
  • 50
ChrisF
  • 134,786
  • 31
  • 255
  • 325
11

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.

Maiko Kingma
  • 929
  • 3
  • 14
  • 29
1

To handle multiple modifiers keys ( In KeyDown event)

 if (e.Control && e.Shift)
            {
                if (e.KeyCode == Keys.F1)
                {
                    // Your code goes here

                }
            }
Hasan Shouman
  • 2,162
  • 1
  • 20
  • 26