简体   繁体   中英

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).

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. Then you will know which keys are down at the time of any KeyDown event.

  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.

  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.

Perhaps calling GetKeyboardState() will be most convenient.

For example, to declare the P/Invoke:

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

The inside your KeyDown handler do something like this:

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.

你一定要这样

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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