C#:从 KeyEventArgs 的 KeyData 获取正确的按键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/865774/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 04:46:10  来源:igfitidea点击:

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

c#enumsenum-flagskeyeventargs

提问by Andreas Grech

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

我诱捕KeyDown事件,我需要能够检查当前键是否按下为:Ctrl+ Shift+ M



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

我知道我需要使用e.KeyDatafrom KeyEventArgsKeysenum 和带有 Enum Flags 和位的东西,但我不确定如何检查组合。

采纳答案by Mike Dinescu

You need to use the Modifiersproperty of the KeyEventArgs class.

您需要使用KeyEventArgs 类的Modifiers属性。

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

回答by Eric

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.

这与正常的密钥检查相结合,将为您提供所需的答案。

回答by Ivandro Ismael Gomes Jao

I think its easiest to use this:

我认为最容易使用这个:

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

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