views:

1847

answers:

2

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.

+5  A: 

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 Ctrl + Shit + 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");
}
Miky Dinescu
Excellent. Exactly what I was looking for. Thanks for the answer.
Andreas Grech
Glad I could help. I know I was frustrated with this stuff one day.. ;)
Miky Dinescu
A: 

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.

Eric
That does not work. The ModifierKeys--without masking--cannot possibly be equal to two different values simultaneously :-)
msorens
It's a bit-wise operation, and it does work. I've done it.
Eric