5

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. Commented Nov 29, 2012 at 0:25
  • If your game logic is in a real-time event loop, you could just call it: Form_KeyDown(null, e) Commented Nov 29, 2012 at 0:26

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Keeping track of keydowns and keyups is the only way I've found to handle this. I have an array with 255 ints, each element corresponding to a keycode. Each time through the loop I set them to 0 (not pressed), 1 (newly pressed), or 2 (still pressed). I did that because some functionality you'll want continuously (like using cursor keys to move) and some you'll only care about the initial keypress (like 'M' to toggle HUD).
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.