Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Getting the correct keys pressed from KeyEventArgs' KeyData

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.

like image 715
Andreas Grech Avatar asked Dec 22 '22 11:12

Andreas Grech


2 Answers

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");
}
like image 172
Mike Dinescu Avatar answered May 01 '23 04:05

Mike Dinescu


I think its easiest to use this:

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

like image 21
Ivandro Jao Avatar answered May 01 '23 04:05

Ivandro Jao