我正在学习使用kbhit()
,GetAsyncKeyState()
和getch()
的组合来构建我的控制台游戏。
我正在使用visual studio 2010 express,c / c ++标题对我来说没问题。
兼容性问题(仅在Windows平台上运行)对我来说无关紧要。
看看这个简单的代码:
#include<stdio.h>
#include<conio.h>
#include<Windows.h>
int main()
{
printf("Welcome\n");
while(true)
{
if(_kbhit())
{
if(GetAsyncKeyState(VK_UP))
printf("UP\n");
else if(GetAsyncKeyState(VK_DOWN))
printf("DOWN\n");
else if(GetAsyncKeyState(VK_LEFT))
printf("LEFT\n");
else if(GetAsyncKeyState(VK_RIGHT))
printf("RIGHT\n");
else
printf("NOT ARROW\n");
getch();
}
}
return 0;
}
问题是:任何虚拟键输入都会打印 TWICE ,而其他虚拟键输入则运行正常。
我不知道问题是什么,但我发现它很容易解决。
#include<stdio.h>
#include<conio.h>
#include<Windows.h>
int main()
{
printf("Welcome\n");
while(1)
{
if(_kbhit())
{
if(GetAsyncKeyState(VK_UP))
{
printf("UP\n");
_getch();
}
else if(GetAsyncKeyState(VK_DOWN))
{
printf("DOWN\n");
_getch();
}
else if(GetAsyncKeyState(VK_LEFT))
{
printf("LEFT\n");
_getch();
}
else if(GetAsyncKeyState(VK_RIGHT))
{
printf("RIGHT\n");
_getch();
}
else
{
printf("NOT ARROW\n");
}
_getch();
}
}
return 0;
}
我的猜测GetAsyncKeyState()
未正确清除为默认值
任何解释?
同样为每_getch()
和kbhit()
添加GetAsyncKeyState()
是一种减少因此降低可读性,任何替代方案?
答案 0 :(得分:0)
(GetAsyncKeyState(VK_UP)&amp; 1 )