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:
- Presses the 1 key.
- Releases the 1 key.
- Presses and releases the following keys: 'H', 'i', 'S', 't', 'a', 'c', 'k', 'o', 'v', 'e', 'r', 'f', 'l', 'o', 'w', and '2'.
- Presses and releases the control key.
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.
GetAsyncKeyState, but would a compoundifstatement work?if(GetAsyncKeyState(VK_CONTROL) && GetAsyncKeyState('1'))?GetAsyncKeyStateshould be masked with 0x8000 to check if the key is down (as per the documentation). Anyway, hotkeys can be set usingRegisterHotKey.GetAsyncKeyStateanswers the question of "Is this key down right now?", not the question of if they were pressed at the same time, any keys were pressed in the middle, or a cat is on your keyboard. If you need to track those things you need to provide that additional logic yourself or choose a different method of handling input.