开发者

How to simulate a key press in C++

I was wondering how can I simulate a key depression in C++. Such as having code that when I run the program it presses the letter "W" key. I don't want to be displaying it in a console window I just want it to display the "W" key every time I click on a text field. Thanks!

Note: I am not trying to make 开发者_JAVA百科a spammer.


It looks like you want to use either SendInput() or keybd_event() (which is an older way of doing the same thing).


First - find this answer on how to use sendinput function in C++.

Look at the code section:

// ...
    INPUT ip;
// ...
    // Set up a generic keyboard event.
    ip.type = INPUT_KEYBOARD;
    ip.ki.wScan = 0; // hardware scan code for key
    ip.ki.time = 0;
    ip.ki.dwExtraInfo = 0;

    // Press the "A" key
    ip.ki.wVk = 0x41; // virtual-key code for the "a" key
    ip.ki.dwFlags = 0; // 0 for key press
    SendInput(1, &ip, sizeof(INPUT));
// ...

I didn't understand where the magic number 0x41 came from.

Go to SendInput documentation page. Still don't understand where's the 0x41.

Go to INPUT documentation and from there to KEYBDINPUT documentation. Still no magic 0x41.

Finally go to Virtual-Key Codes page and understand that Microsoft has given the names for Ctrl (VK_CONTROL), Alt (VK_MENU), F1-F24 (VK_F1 - VK_F24, where are 13-24 is a mystery), but forgot to name characters. Actual characters have codes (0x41-0x5A), but don't have names like VK_A - VK_Z I was looking for in winuser.h header.


My two cents in this. Character "A" in ASCII is 65 in decimal. But in HEX is 41. Hence, 0x41

Look here for the ASCII table http://www.asciitable.com/

Maybe you would be interested in the SCAN codes as well, not just in ASCII. SCAN codes can even tell (and simulate) when the key is downpressed, but also when that key is actually released. SCAN codes are usually followed as well by the ASCII codes in the "input buffer". Here, about the "input buffer" (which is actually a FIFO list in RAM): How to clear input buffer in C?

Here is a small example: http://csourcecodes.blogspot.com/2014/08/c-program-to-display-scan-and-ascii.html

If you're using Windows - possibly your best approach would be the "SendInput" mentioned earlier. Here is a small doc about that: https://batchloaf.wordpress.com/2012/04/17/simulating-a-keystroke-in-win32-c-or-c-using-sendinput/

Hope it helps you - at least a bit!... :)

success!...

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜