-->

Keypress event in C++

2019-02-20 10:19发布

问题:

I'm currently using GetAsyncKeyState() to detect Keydown events, but then the events will be repeated while you are holding down the key.

What would be an easy way to stop the event from repeating?


Example

If I hold down the key i on my keyboard for a while, I will get an output like this:

iiiiiiiiiiiiiiiiiiiiiiiii

Instead of this:

i


I want to force the user to press the key again to trigger the event.

回答1:

Avoid using a keyboard related message like WM_KEYDOWN or WM_CHAR to detect a key, Windows repeats WM_KEYDOWN when the user holds it down. You simply need a your own bool flag that keeps track of the state of the key. Only change your game object state when you see a difference between the state as reported by GetAsyncKeyState() and this flag. Roughly:

bool movingLeft = false;
...
if ((GetAsyncKeyState(VK_LEFT) < 0) != movingLeft) {
    movingLeft = !movingLeft;
    gameObject->setVelocity(movingLeft ? -10 : 0);
}


回答2:

Use KeyPress events (or KeyUp).

Btw according to MSDN SHORT WINAPI GetAsyncKeyState(__in int vKey);

Determines whether a key is up or down at the time the function is called, and whether the key was pressed after a previous call to GetAsyncKeyState.

It doesn't say anything about detecting a keydown event.