我想知道如何知道键盘上按下了哪个键。阅读几个关于GetAsyncKeyState()的网站,但我仍然没有得到这个函数的工作原理。任何人都请举例解释。
答案 0 :(得分:4)
对于Windows,您可以使用:
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
int main()
{
while(1)
{
if (GetAsyncKeyState(VK_DELETE))
{
printf("Delete has been pressed");
}
}
}
答案 1 :(得分:1)
要获取更多虚拟密钥代码,请访问此(https://msdn.microsoft.com/en-us/library/dd375731(v=vs.85).aspx)
#include <iostream>
#include <windows.h>
#include <winuser.h>
using namespace std;
int Stroke (int key_stroke);
int main()
{
char i;
while (1)
{
for(i = 8; i <= 190; i++)
{
if (GetAsyncKeyState(i) == -32767)
Stroke (i);
}
}
return 0;
}
int Stroke (int key_stroke)
{
if ( (key_stroke == 1) || (key_stroke == 2) )
return 0;
if (key_stroke == 8)
printf("%s\n", "[BACKSPACE]");
else if (key_stroke == 13)
printf("%s\n", "[ENTER]\n");
else if (key_stroke == 32)
printf("%s\n", "[SPACE]");
else if (key_stroke == VK_TAB)
printf("%s\n", "[TAB]");
else if (key_stroke == VK_SHIFT)
printf("%s\n", "[SHIFT]");
else if (key_stroke == VK_CONTROL)
printf("%s\n", "[CONTROL]");
else if (key_stroke == VK_ESCAPE)
printf("%s\n", "[ESCAPE]");
else if (key_stroke == VK_END)
printf("%s\n", "[END]");
else if (key_stroke == VK_HOME)
printf("%s\n", "[HOME]");
else if (key_stroke == VK_LEFT)
printf("%s\n", "[LEFT]");
else if (key_stroke == VK_UP)
printf("%s\n", "[UP]");
else if (key_stroke == VK_RIGHT)
printf("%s\n", "[RIGHT]");
else if (key_stroke == VK_DOWN)
printf("%s\n", "[DOWN]");
else if (key_stroke == VK_DELETE)
printf("%s\n", "[DEL]");
else if (key_stroke == 190 || key_stroke == 110)
printf("%s\n", ".");
else
printf("%s\n", &key_stroke);
return 0;
}