user3493681
user3493681

Reputation:

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.

Upvotes: 0

Views: 2458

Answers (3)

Matthew Watson
Matthew Watson

Reputation: 109567

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.

Upvotes: 1

Furquan Khan
Furquan Khan

Reputation: 1594

You got to do like this

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

Upvotes: 0

Tigran
Tigran

Reputation: 62246

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.

Upvotes: 3

Related Questions