简体   繁体   English

C#需要如果语句来检查空间和箭头键按下

[英]c# need if statement to check for space and arrow keys pressed

if (e.KeyCode == Keys.Space && e.KeyCode == Keys.Right)
{
    //do stuff 
}

basically its not reading the space bar and the right arrow keys being pressed at the same time. 基本上,它不会同时阅读空格键和向右箭头键。

you need to understand if the resulting code contains all keys you need (because it is an aggregated result of multiple keys pressed in the same moment) 您需要了解结果代码是否包含所需的所有键(因为它是同一时间按下多个键的汇总结果)

so you may do like: 因此您可能会喜欢:

if((e.KeyCode | Keys.Space == e.KeyCode) && 
      (e.KeyCode | Keys.Right== e.KeyCode)) //BINARY OR EXECUTION 

OR 要么

x  y  result
------------
1  1     1
1  0     1 //CHANGED !=x
0  1     1 //CHANGED !=x
0  0     

Basic idea is: if i execute binary OR on the number with another that is inside it, the result has to be the same like an original number. 基本思想是:如果我对数字与其中的另一个数字执行二进制或运算 ,则结果必须与原始数字相同。

The standard .Net framework doesn't let you directly check if multiple keys are pressed (other than modifier keys such as Ctrl, Shift and Alt). 标准的.Net框架不允许您直接检查是否按下了多个键(除了Ctrl,Shift和Alt等修饰键之外)。

There are at least three possible solutions: 至少有三种可能的解决方案:

  1. Maintain your own state array of the keys that you are interested in, and update the state on every KeyDown and KeyUp event. 维护您自己感兴趣的键的状态数组,并在每个KeyDown和KeyUp事件上更新状态。 Then you will know which keys are down at the time of any KeyDown event. 然后,您将知道在任何KeyDown事件发生时哪些键已按下。

  2. In your KeyDown handler use P/Invoke to call the Windows API GetKeyboardState() function to check the state of all the keys you're interested in. 在KeyDown处理程序中, 使用P / Invoke调用Windows API GetKeyboardState()函数以检查您感兴趣的所有键的状态。

  3. In your KeyDown handler use P/Invoke to call the Windows API GetKeyState() function to determine the key state for each key that you're interested in. 在KeyDown处理程序中, 使用P / Invoke调用Windows API GetKeyState()函数来确定您感兴趣的每个键的键状态。

Perhaps calling GetKeyboardState() will be most convenient. 也许调用GetKeyboardState()最方便。

For example, to declare the P/Invoke: 例如,声明P / Invoke:

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetKeyboardState(byte[] lpKeyState);

The inside your KeyDown handler do something like this: 您的KeyDown处理程序内部执行以下操作:

byte[] keys = new byte[255];
GetKeyboardState(keys);

// keys[x] will be 129 if the key defined by x is down.

if ((keys[(int)Keys.Space] == 129) && (keys[(int)Keys.Right] == 129))
    ... Space and Right are both pressed

Please read the comments on PInvoke.Net for caveats and further advice. 请阅读PInvoke.Net上的注释以获取警告和进一步的建议。

你一定要这样

if((e.KeyCode | Keys.Space == e.KeyCode) && (e.KeyCode | Keys.Right== e.KeyCode))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM