Home > OS >  Ctrl still pressed with keyb_event()
Ctrl still pressed with keyb_event()

Time:05-08

i'm trying to help a friend with a macro for his mouse, but i've been strugling with an error.

But when i use :

if(GetAsyncKeyState(VK_XBUTTON2)){

keybd_event(VK_LCONTROL, 0xA2, 0x0001, 0); 
    Sleep(50);

keybd_event(VK_LCONTROL, 0xA2, 0x0002, 0);
    Sleep(50); }

My ctrl still holded unless i click in my console and press ctrl again.

CodePudding user response:

Don't use magic numbers in your code, it makes it harder to read and understand. Use named constants instead. In this case, KEYEVENTF_EXTENDEDKEY and KEYEVENTF_KEYUP. Then you will notice that you are not specifying the KEYEVENTF_EXTENDEDKEY flag when releasing the key. Use the | (bitwise OR) operator to combine flags.

Also, don't hard-code the scan code, as it may differ on different machines. Use MapVirtualKey() instead.

Try this:

const BYTE scanCode = MapVirtualKey(VK_LCONTROL, MAPVK_VK_TO_VSC);

...

if (GetAsyncKeyState(VK_XBUTTON2)){

    keybd_event(VK_LCONTROL, scanCode, KEYEVENTF_EXTENDEDKEY, 0); 
    Sleep(50);

    keybd_event(VK_LCONTROL, scanCode, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
    Sleep(50);
}

That said, keybd_event() is deprecated, use SendInput() instead:

INPUT input = {};
input.type = INPUT_KEYBOARD;
input.ki.wVk = VK_LCONTROL;
input.ki.dwFlags = KEYEVENTF_EXTENDEDKEY;

...

if (GetAsyncKeyState(VK_XBUTTON2)){

    input.ki.dwFlags &= ~KEYEVENTF_KEYUP;
    SendInput(1, &input, sizeof(INPUT));
    Sleep(50);

    input.ki.dwFlags |= KEYEVENTF_KEYUP;
    SendInput(1, &input, sizeof(INPUT));
    Sleep(50);
}
  • Related