Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 701
llk Avatar asked Apr 09 '11 20:04

llk


People also ask

How do you simulate keystrokes?

To simulate native-language keystrokes, you can also use the [Xnn] or [Dnn] constants in the string passed to the Keys method. nn specifies the virtual-key code of the key to be “pressed”. For instance, [X221]u[X221]e will “type” the u and e characters with the circumflex accent.

How do you check if a key is pressed in C?

kbhit() is present in conio. h and used to determine if a key has been pressed or not. To use kbhit function in your program you should include the header file “conio.

How do you press a key in C++?

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


2 Answers

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

like image 200
Greg Hewgill Avatar answered Oct 01 '22 22:10

Greg Hewgill


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.

like image 20
jtheterrible Avatar answered Oct 01 '22 21:10

jtheterrible