Reputation: 11
main.c:
#include <stdio.h>
#include <windows.h>
#include <stdbool.h>
int main(void) {
while (true) {
if (GetAsyncKeyState(VK_CONTROL)) {
if (GetAsyncKeyState('1')) {
printf("Set grenades to 100!\n");
Sleep(500);
}
}
Sleep(100);
}
return 0;
}
I've tried changing between debug and release mode, between the mingw and VS compilers, and I tired both C and C++. The same bug happens in all cases.
The idea is so that the hotkey is Control + 1. Whenever the user presses both the Control key and the 1 key at the same time, I want the code printf("Set grenades to 100!\n");
to be ran.
However, there is a bug. If the user presses and release the 1 key. Waits any amount of time (seconds, minutes) and then presses the Control key, printf("Set grenades to 100!\n");
is executed.
This bug happens even if the user presses keys in between. For example: printf("Set grenades to 100!\n");
is executed if the user does the following:
On step 4, the code is executed. How do I fix this bug?
I want to use GetAsyncKeyState not GetKeyState because I want the input to be captured even if the user switches to another program.
Upvotes: 1
Views: 1189
Reputation: 23208
Regarding the return value of GetAsyncKeyState()
, according to Microsoft, If the most significant bit is set, the key is down.
An important take-away here is: for signed types, such as short
, when the most significant bit is set, it is read as a negative number. GetAsyncKeyState()
returns short
.
This suggests the logic used in your code to interpret the result of GetAsyncKeyState()
is opposite of what it needs to be in its current application. That is, your condition statement should be checking for negative numbers instead of positive.
One more note: as others have suggested, the purpose of GetAsyncKeyState()
is to check the condition of the key now. But it's return value also contains information to determine whether the key has been pressed recently. In fact, that is what you would be doing by looking at the LSB. In the same link, it is explained that the LSB is an indicator of recent status However this is not a recommended practice. The recent bit status can be set by any process running in another thread, at any time, therefore, should only be used with caution.
So, try this instead. I tested this on 64 bit windows, it seems to work fine, no matter how many times I press the 1 first, or press the ctrl
key, the popup does not occur. But, when I press both simultaneously, then it pops up.
#include <stdio.h>
#include <windows.h>
//#include <stdbool.h>//I did not need this, you might.
int main(void) {
while (1)
{
if (GetAsyncKeyState(VK_CONTROL)<0)
{
if (GetAsyncKeyState('1')<0)
{
printf("Set grenades to 100!\n");
Sleep(200);//changed here for my test, you might need to change again
}
}
Sleep(200);//changed here for my test, you might need to change again
}
return 0;//unreachable code warning
}
Upvotes: 1