在C ++中按键事件 [英] Keypress event in C++

查看:207
本文介绍了在C ++中按键事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前使用 GetAsyncKeyState()来检测Keydown事件,但是在按住键的同时会重复这些事件。

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

如果我按住键 i 在我的键盘上一段时间,我会得到这样的输出:

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

iiiiiiiiiiiiiiiiiiiiiiiii

而不是这样:

i





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

推荐答案

避免使用类似WM_KEYDOWN或WM_CHAR的键盘相关消息检测键,当用户将其关闭时,Windows会重复WM_KEYDOWN。你只需要一个自己的bool标志来跟踪密钥的状态。只有当您看到GetAsyncKeyState()报告的状态和此标志之间的差异时,才更改游戏对象状态。大致:

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

这篇关于在C ++中按键事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆