使用 GetKeyState()
我希望在按下按键时有一个布尔事件切换。具体来说,是 's' 键。我被指出函数 GetKeyState(),据说它在 Win32 API 下工作。我知道字母“s”的 ASCII 代码是 115,所以我的代码如下:
if (GetKeyState(115) == 1)
{
<EVENT>
}
但是,这不起作用。为什么?以下是 MSDN 参考: http://msdn .microsoft.com/en-us/library/ms646301%28v=vs.85%29.aspx ...“如果低位为1,则密钥已切换”
I would like to have a boolean event toggle when a key is pressed. Specifically, the 's' key. I have been pointed to the function GetKeyState(), which supposedly works under the Win32 API. I understand the ASCII code for the letter 's' is 115, and so my code is as follows:
if (GetKeyState(115) == 1)
{
<EVENT>
}
However, this does not work. Why? Here is the MSDN reference: http://msdn.microsoft.com/en-us/library/ms646301%28v=vs.85%29.aspx ... "If the low-order bit is 1, the key is toggled"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
据我了解,你需要做的:
最高位告诉是否按下了键。最低的表示按键是否已切换(例如,大写锁定是否已打开)。
From what I understand you need to do:
The highest bit tells if key is pressed. The lowest tells if key is toggled (like, if caps lock is turned on).
由于 SHORT 有符号,因此高位等于符号位。
因此,要测试是否按下给定的键,只需测试
GetKeyState()
返回的值是否为负:此外,115 是 's' 的 ASCII 代码。我相信,您应该使用大写字母 83 来测试“S”键。
Since SHORT is signed, high-order bit equals sign bit.
Therefore to test if a given key is pressed, simply test if the value returned by
GetKeyState()
is negative:Besides, 115 is ASCII code for 's'. I believe, you should use capital case 83 to test the 'S' key.
我使用全局变量 bool
altgr
示例:
I use a global variable bool
altgr
Example:
有时您想使用组合键。
为了避免组合键(例如:VK_SHIFT && VK_LEFT)满足两个条件的情况:
只需使用
Sleep(...);
和GetAsyncKeyState(VK_...) < /代码>
<一href="https://stackoverflow.com/questions/17770753/getkeystate-vs-getasynckeystate-vs-getch/17771038">GetKeyState() 与 GetAsyncKeyState() 与 getch() 比较?
Sometimes you want to use a combination of keys.
To avoid the situations when a combination of keys (eg: VK_SHIFT && VK_LEFT) satisfies two conditions:
just use
Sleep(...);
andGetAsyncKeyState(VK_...)
GetKeyState() vs. GetAsyncKeyState() vs. getch()?
有点晚了,但高位是 0x80000000 而不是 0x8000,改变它,它会正常工作。
另一位 - 无用 - 它的作用就好像你在按下 LSHIFT 时按下了 CAPS LOCK。
Bit late for this but the high order bit is 0x80000000 not 0x8000, change this and it will work fine.
The other bit - useful for nothing - it acts as if you pressed CAPS LOCK when you pressed LSHIFT.