Home > Blockchain >  GetAsyncKeyState with held CTRL button and another "toggled" button not working as wanted
GetAsyncKeyState with held CTRL button and another "toggled" button not working as wanted

Time:01-03

I got the following code for testing purposes:

bool test = false;
if (GetAsyncKeyState(VK_LCONTROL) && GetAsyncKeyState(VK_F2) & 1) {
    test = !test;
    std::cout << test << std::endl;
}

Now what I would like to happen is when I hold down the left control and then press F2 that the instructions are being properly handled. The problem is that the condition turns to true if I hold LCTRL and then F2 or when I hold F2 and then press LCTRL or when I press LCTRL and then press F2 or when I press F2 and then LCTRL. So no matter which combination of which button to press I use the condition always turns out to be true.

I hope some of you people encountered this at some point and can help with some very much appreciated insight.

CodePudding user response:

GetAsyncKeyState returns multiple things in its return value. The correct way to check if a key is down is: bool lctrldown = GetAsyncKeyState(VK_LCONTROL) < 0;

That being said, waiting for a user to press F2 implies polling and polling is bad! If you only care about F2 in your own window then you should use TranslateAccelerator in your message loop or handle WM_KEYDOWN.

For a global solution, use RegisterHotKey or a low-level keyboard hook.

In the case of WM_KEYDOWN or a hook, when you get notified about F2 you should then check the state of the control key with GetAsyncKeyState.

  • Related