开发者

Keypress event in C++

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开发者_如何学运维.


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);
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜