Keybd_event does not work correctly = (

I cannot get this to work correctly. This should press the left button for 1 second, then wait 10 seconds, then right 1 second, etc .:

keybd_event(0x25, 0xCB, 0, 0);  // press left
cout << "Ldown\n";              // so i know it worked

Sleep(1000);                    // hold it for 1sec
keybd_event(0x25, 0xCB, KEYEVENTF_KEYUP, 0);// let go of the key
cout << "Lup\n";                // so i know i let go
Sleep(10000);                   // Sleep for 10secs

keybd_event(0x27, 0xCD, 0, 0);  // press right
cout << "Rdown\n";              // so i know i pressed right
Sleep(1000);                    // sleep 1sec
keybd_event(0x27, 0xCD, KEYEVENTF_KEYUP, 0);// let go of the key
cout << "Rdown\n";              // so i know i let go.

This is in a loop, but it won’t do anything :( If I don’t close the program before the key is released, then it just holds the key until I press the key again.

I know that you can use only one key code if you want, but I need to use both.

So what am I missing?

+3
source share
2 answers

This code works for me. I cleaned it a bit (no magic numbers !, use MapVirtualKey, helper functions, etc.):

#include <iostream>
#include <windows.h>

// for key pushing
BYTE scan_code(DWORD pKey)
{
    const DWORD result = MapVirtualKey(pKey, MAPVK_VK_TO_VSC);

    return static_cast<BYTE>(result);
}

void press_key(DWORD pKey)
{
    keybd_event(static_cast<BYTE>(pKey), scan_code(pKey), 0, 0);
}

void release_key(DWORD pKey)
{
    keybd_event(static_cast<BYTE>(pKey), scan_code(pKey), KEYEVENTF_KEYUP, 0);
}

// for testing
#define PRESS(x) press_key(x); std::cout << "Press: " #x << std::endl
#define RELEASE(x) release_key(x); std::cout << "Release: " #x << std::endl

// test
int main(void)
{
    for (;;)
    {
        PRESS(VK_LEFT);
        Sleep(10); // hold it for 1/100'th of a second

        RELEASE(VK_LEFT);
        Sleep(1000); // wait for a second

        PRESS(VK_RIGHT);
        Sleep(10); // hold it for 1/100'th of a second

        RELEASE(VK_RIGHT);
        Sleep(1000); // wait for a second
    }
}

, , , . . ?

+3

" "? ? std:: endl, , GMan, "\n", endl .

+1

Source: https://habr.com/ru/post/1739556/


All Articles