Multiple key events at same time?

etherias

Member
Joined
May 5, 2010
Messages
5
Programming Experience
1-3
How can i code my application so that it can handle two sets of key events at the same time? For example, if I was making a game where one player used the WASD, and the other the arrow keys for moving, how can i make it so that both can move at the same time? The code I used only allows one to move at a time.. (key press event, If e.KeyData = Windows.Forms.Keys.down then.... etc)

Thanks! And nice to meet everyone :D

(Does it have to do with multithreading...?)
 
You are mistaken. The KeyPress event has no e.KeyData property. KeyPress has e.KeyChar because it's designed to detect characters, while the KeyDown and KeyUp events have e.KeyCode and e.KeyData because they are designed to detect keys.

You can simply handle the KeyDown event and test e.KeyData for all the keys your interested in, e.g.
VB.NET:
If (e.KeyData And Keys.W) = Keys.W Then
    'The W key is down.
End If
If (e.KeyData And Keys.A) = Keys.A Then
    'The A key is down.
End If
'Etc.
The only problem with that is that there's a longer gap between the first and second events than there is between all the others when you hold a key down for an extended period. If you depress one key and it starts repeating, then you depress another key, there will be a longer gap to the next event, which will affect the first key too. If that's a problem, you might want to instead use a Timer and call the GetAsyncKeyState API so that the gap between two detections is always the same.
 

Latest posts

Back
Top