5
votes

I am doing a little game with sprites where the character moves depending on the pressed key (arrows). I've noticed that the .KeyDown() method keeps being called until any key is released.

e.g. When the user is pressing the up arrow, the method of .KeyDown() keeps being called. If the down arrow is pressed, still with the up arrow pressed, the KeyEventArgs receives now the input from the down arrow. Finally, when the up arrow is released, the .KeyDown()event stops being called even though the down arrow is still pressed.

How do I "reset" the input and tell the compiler to keep calling .KeyDown()?

2
Have you tried logging which key is responsible for the KeyDown so you can check when you get a key release? This way, you can keep going as if the Key is still down until the key you are interested in is the one that initiated the release. - RonaldBarzell
If your game logic is in a real-time event loop, you could just call it: Form_KeyDown(null, e) - Jeremy Thompson

2 Answers

3
votes

A very good question- I don't believe that there's any way to override this default behavior, but it would certainly be possible to avoid this effect by keeping track of key presses yourself- i.e., when .KeyDown() is called, add the key to some type of structure which keeps track of it- and then, when .KeyUp() is called, remove the key from that structure.

Then, just repeatedly check that structure for the currently pressed keys, and base your movement off of that, not what .KeyDown() is telling you.

0
votes

You can try to use KeyUp in order to detect when the key is released. Then you can assume the key is still pressed until KeyUp is called.