Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Ctrl still pressed with keyb_event()

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading