Reputation: 27
Using GetKeyState, I can do some task when a key is pressed. However, if I have if (GetKeyState(VK_UP) & 0x80)
, it returns true the entire time the key is being held.
How do I handle this if I just want this to be true the exact moment the key is pressed (so the contents of the if statement don't run several times)?
Upvotes: 0
Views: 1327
Reputation: 100
I know this thread is old and all, but i approached this a bit different than the others and thought of sharing my solution here.
bool previousKeyDown = GetKeyState(VK_...) & 1;
while (true) {
bool keyDown = GetKeyState(VK_...) & 1;
if(keyDown != previousKeyDown) {
previousKeyDown = f6Down;
}
}
Here i am using the toggle bit to exploit the toggle behaviour of usually non toggleable keys.
Its nice and short.
Upvotes: 0
Reputation: 98816
Remember what the state was last time through the loop, and only execute your code if the key was up before and is now down.
Also, you seem to be checking if the high bit is set by masking the result with 0x80, but SHORT is two bytes. I think you should be using 0x8000; alternatively, you can check if the result is < 0, since the high bit indicates whether a signed integer is negative or not.
The code would look something like this:
bool prevUpKeyState = false; // false indicates key was up
while (...) {
// ...
bool currentUpKeyState = GetKeyState(VK_UP) < 0;
if ((currentUpKeyState) && (!prevUpKeyState)) {
// Key just depressed, do stuff
}
// ...
// Update previous key state for next pass through loop:
prevUpKeyState = currentUpKeyState;
}
Upvotes: 1
Reputation: 11232
You can use a bool flag = false
and use it like this:
if((GetKeyState(VK_UP)&0x80) && ! flag)
{
flag = true;
}
else if((GetKeyState(VK_DOWN)&0x80) && flag)
{
flag = false;
}
if(flag) //key is just pressed
{
//TODO: Your handling here
}
Upvotes: 1