开发者

keybd_event is not working right =(

I can't get this to work right. This should press left 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开发者_StackOverflow, 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 wont do anything :( Unless I close the program before the key is let go, then it will just keep the key down until I press the key again.

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

So what am I missing?


The code seems to work for me. I cleaned it up 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
    }
}

I tested by opening Notepad, typing a bunch of characters, then ran the program. The caret moved back and forth. How are you testing it?


How are you measuring "doesn't do anything"? Is it just that no output appears? Use std::endl to end your lines, as GMan does, instead of "\n", because endl performs a flush in addition to outputting a newline character.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜