How to simulate a key press in C++

100,844

Solution 1

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

Solution 2

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.

Share:
100,844
llk
Author by

llk

Updated on July 09, 2022

Comments

  • llk
    llk almost 2 years

    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 a spammer.