Keypress event in C++

天大地大妈咪最大 提交于 2019-12-01 10:49:30

问题


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.



来源:https://stackoverflow.com/questions/5523111/keypress-event-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!