4

I am trapping a KeyDown event and I need to be able to check whether the current keys pressed down are : Ctrl + Shift + M ?


I know I need to use the e.KeyData from the KeyEventArgs, the Keys enum and something with Enum Flags and bits but I'm not sure on how to check for the combination.

Andreas Grech
  • 105,982
  • 98
  • 297
  • 360

3 Answers3

12

You need to use the Modifiers property of the KeyEventArgs class.

Something like:

//asumming e is of type KeyEventArgs (such as it is 
// on a KeyDown event handler
// ..
bool ctrlShiftM; //will be true if the combination Ctrl + Shift + M is pressed, false otherwise

ctrlShiftM = ((e.KeyCode == Keys.M) &&               // test for M pressed
              ((e.Modifiers & Keys.Shift) != 0) &&   // test for Shift modifier
              ((e.Modifiers & Keys.Control) != 0));  // test for Ctrl modifier
if (ctrlShiftM == true)
{
    Console.WriteLine("[Ctrl] + [Shift] + M was pressed");
}
ajaysinghdav10d
  • 1,771
  • 3
  • 23
  • 33
Mike Dinescu
  • 54,171
  • 16
  • 118
  • 151
1

I think its easiest to use this:

if(e.KeyData == (Keys.Control | Keys.G))

Ivandro Jao
  • 2,731
  • 5
  • 24
  • 23
-2

You can check using a technique similar to the following:

if(Control.ModifierKeys == Keys.Control && Control.ModifierKeys == Keys.Shift)

This in combination with the normal key checks will give you the answer you seek.

Andreas Grech
  • 105,982
  • 98
  • 297
  • 360
Eric
  • 464
  • 3
  • 7
  • That does not work. The ModifierKeys--without masking--cannot possibly be equal to two different values simultaneously :-) – Michael Sorens May 16 '10 at 17:48
  • 1
    I know this is a bit old but, it doesn't work, you've got to mask it first... if ((Control.ModifierKeys & Keys.Control) == Keys.Control && (Control.ModifierKeys & Keys.Shift) == Keys.Shift) – Chris McGrath Apr 03 '11 at 05:51