简体   繁体   English

C++ 如何将用户按键存储在变量中

[英]C++ How to store user key press inside a variable

So, I already know that by using if (GetAsyncKeyState()) I can check if the user presses a specific key.所以,我已经知道通过使用if (GetAsyncKeyState())我可以检查用户是否按下了特定的键。 But what I need is to check if the user presses any key and to store that key that the user pressed inside a variable.但我需要检查用户是否按下任何键并将用户按下的键存储在变量中。 Is there any easy way to do that?有什么简单的方法可以做到这一点吗?

First, _getch could read a single character from the console without echoing the character.首先, _getch可以从控制台读取单个字符而不回显该字符。 But it has limitations, it cannot read all keys.但它有局限性,它不能读取所有密钥。

Then, GetKeyboardState can get the status of the 256 virtual keys.然后, GetKeyboardState可以获取 256 个虚拟键的状态。 But it cannot detect the key event between two calls.但它无法检测到两个调用之间的关键事件。

You could register key down event with RawInput or LowLevelKeyboard hook , Check this sample , you will get the Virtual-Key in input.data.keyboard.VKey .您可以使用RawInputLowLevelKeyboard 挂钩注册按键事件,检查此示例,您将在input.data.keyboard.VKey中获得虚拟键 You could create a thread to wait and get the key event, instead of polling to check key status.您可以创建一个线程来等待并获取键事件,而不是轮询来检查键状态。

I'm guessing you're trying to get input without the user pressing 'Enter', in that case see this post's answer .我猜您正在尝试在用户不按“Enter”的情况下获取输入,在这种情况下,请参阅这篇文章的答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM