Hi!
Well, you kind of mentioned the solution.
We need to memorize the last state.
Let's see whether we can make some little helper for that.
First, some function that checks for keydown. (Jep, thats not what you want, but we will build up on that.)
// Checks whether a key is down.
bool IsKeyDown(char key)
{
return GetAsyncKeyState(key) < 0;
}
Now comes the interesting part: the key press method.
We need to memorize the last state, right? We could either build a class for that and keep it somewhere static (too much stuff to build around that..) or we could use global variables (uh, global scope..).
Instead, let's write a global function that declares static variables in it. The beauty of it is we get a variable with global lifetime (like we would get with a global variable) but only with local scope (not like a global variable!).
// Checks whether a key is pressed.
bool IsKeyPressed(char key)
{
static bool keys[256]; // One flag for each key... local scope but global lifetime!
bool currState = IsKeyDown(key); // get current state.
if (currState && !keys[key]) // compare to last state -> is pressed?
{
keys[key] = currState; // memorize state for next time
return true; // report: yes!
}
keys[key] = currState; // memorize state for next time
return false; // report: no!
}
Well, and just a quick test to see whether it works...
int _tmain(int argc, _TCHAR* argv[])
{
while (!IsKeyDown('E'))
{
if (IsKeyPressed(VK_DOWN))
printf("Pressed!");
Sleep(10);
}
return 0;
}
Looks fine on my side.
Cheers!