【发布时间】:2016-09-05 16:23:01
【问题描述】:
我想了解GetKeyboardState() 的工作原理。我已经阅读了Keyboard Input Model 中对虚拟键的介绍
和GetKeyboardState() documentation。
据我了解,GetKeyboardState() 应该在它返回的数组中声明所有键状态。因此,当我打开和关闭 Caps Lock 键时,我试图查看以下代码是否有任何区别:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <conio.h>
#include <string.h>
#include <windows.h>
#include <iostream>
int main(int argc, char *argv[])
{
INPUT buffer[1];
bool stop = false;
unsigned char kbstate[256];
int timer = 0;
MouseSetup(buffer);
char result = 0;
//doesn't work right now
do{
timer++;
Sleep(3000);
std::cout << "function output: " << GetKeyboardState(kbstate) << std::endl;
for (int i = 0; i < 256; i++) {
std::cout << (int)kbstate[i];
if (i % 16 == 0){
std::cout << std::endl;
}
}
std::cout << std::endl;
} while (!result);
return 0;
}
我的 cap 和 uncap 的输出是一样的。
我猜我理解GetKeyboardState() 的方式是错误的。谁能告诉我哪里出错了?
没关系,我明白了。这是我真正想做的事情。非常感谢大家的帮助。
int main(int argc, char *argv[])
{
INPUT buffer[1];
bool stop = false;
unsigned char ifPress[256];
int timer = 0;
char result = 0;
std::cout << "press any key to quite" << std::endl;
do{
timer++;
Sleep(100);
//check all the status if any key is pressed
for(int i = 0; i < 256; i++) {
ifPress[i] = GetAsyncKeyState(i);
}
//if any key is pressed, change the status to the result
//and the loop will be quit
for (int j = 1; j < 256; j++){
result = result || ifPress[j];
}
} while (!result);
return 0;
}
【问题讨论】:
-
打开和关闭大写锁定不会改变您按下的键。您链接到的文档解释了如何确定 Caps Lock 是否打开。你读了吗?
-
但在 GetKeyboardState 文档中他们说:“如果高位为 1,则键向下;否则,向上。如果键是切换键,例如 CAPS LOCK,那么低位在按键被触发时为 1,如果按键未触发则为 0。低位对于非触发键无意义。切换键被称为打开时被触发。切换键时键盘上的切换键指示灯(如果有)将在切换键时亮起,在键未切换时熄灭。”
-
是的,这部分解释了如何确定 Caps Lock 是否打开。有什么问题?
-
GetKeyboardState() 返回键盘的同步状态,即操作系统上次为您的进程处理输入事件时的状态。这确保了诸如修饰键和死键之类的东西具有正确的状态。当您自己不发送消息循环时,这将不起作用,状态根本不会更新。 C++ 程序的常见问题是,它们的运行时库还不知道电传打字机和终端已过时。然后你必须使用 GetAsyncKeyState()。
-
我认为您跳过了文档中的“当线程从其消息队列中删除键盘消息时,状态会发生变化。当键盘消息发布到线程的消息队列时,状态不会改变”。跨度>