[英]C++ Check if key is pressed, not held down
I have the following code: 我有以下代码:
for (int i = 0; i < 1;) {
if (GetKeyState(VK_SHIFT) & 0x8000)
{
cout << "op";
}
}
This prints out op
if the Shift key is held down, actually it spams the output if you hold down the key. 如果按住Shift键,则会打印出
op
,实际上,如果按住Shift键,它将对输出显示垃圾邮件。
This is what I want instead: 这是我想要的:
The program prints out something ONCE when you press/hold down a key instead of spamming it, and the only way to print it again is to let go of the key and press it again. 当您按下/按住某个键而不是发送垃圾邮件时,程序会一次打印出一些内容,而再次打印该键的唯一方法是放开该键并再次按下。 No matter how long you hold down the key, the program will only execute the following code ONCE, unless you press it again.
无论您按住该键多长时间,该程序只会一次执行以下代码,除非您再次按下该键。
How do I make my code do this? 如何使我的代码做到这一点?
You could simply set a bool
to true
when you've detected a "key down" event and then only set it back to false
once you detect a "key up" event. 您可以在检测到“按键按下”事件时将
bool
设置为true
,然后仅在检测到“按键按下”事件时将其设置回false
。 That way you can know if the key was already down and only report that it was pressed if it was not already in that state. 这样,您可以知道按键是否已经按下,并且仅在按键尚未处于该状态时才报告按键被按下。
Have you used Windows APIs? 您是否使用过Windows API? If not, try
GetKeyState(key) < 0
如果不是,请尝试
GetKeyState(key) < 0
If Windows messages are used with a window callback function, you can use bools array and check the WM_KEYDOWN WM_KEYUP
events. 如果Windows消息与窗口回调函数一起使用,则可以使用bools数组并检查
WM_KEYDOWN WM_KEYUP
事件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.