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

半世苍凉 提交于 2019-12-04 08:44:48

问题


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.


回答1:


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");
}



回答2:


I think its easiest to use this:

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




回答3:


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.



来源:https://stackoverflow.com/questions/865774/c-getting-the-correct-keys-pressed-from-keyeventargs-keydata

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!