I am learning to use combination of kbhit()
, GetAsyncKeyState()
and getch()
to build my console game.
I'm using visual studio 2010 express, c/c++ headers are ok for me.
Compability issues(only run at windows platform) does not matter for me.
Take a look at this simple code:
#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;
}
The problem is: any virtual key input will print TWICE while others runs ok.
I don't know what's the problem, but I've found easy fix for it.
#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;
}
My guess is GetAsyncKeyState()
is not properly cleared to default value
Any explanation?
Also adding _getch()
for every kbhit()
and GetAsyncKeyState()
is kind of redudancy therefore reduce readability, any alternatives?