Dacul Dacul - 1 year ago 146
C++ Question

C++ loop simulate keypress while key is pressed

I am trying to get a small app that will continuously simulate UP (↑ arrow key) while another key is pressed, in my case Right CTRL.

The code I wrote however, will only send one UP for each press - and while I keep Right CTRL pressed, it will only send one UP and stop.

I want to mention that this code is built entirely from documentation I found online, I have never written anything in C++ ever before, or any other language so any suggestions would greatly help me. I initially tried doing this while CAPS LOCK was active, but I found that getting the key state (on/off) did not work for me at all, no matter what I tried.

int main()
// This structure will be used to create the keyboard
// input event.

// Pause for 1 seconds.

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

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


// Release the "UP arrow" key
ip.ki.dwFlags = KEYEVENTF_KEYUP; // KEYEVENTF_KEYUP for key release
SendInput(1, &ip, sizeof(INPUT));


// Exit normally
return 0;

Answer Source

Use GetKeyState instead of GetAsyncKeyState because GetAsyncKeyState will return false if the key wasn't pressed again since the last time it was pressed:

If the function succeeds, the return value specifies whether the key was pressed since the last call to GetAsyncKeyState

GetKeyState will simply give you the status, which is what you want if you're holding down the RCONTROL key:

Retrieves the status of the specified virtual key. The status specifies whether the key is up, down, or toggled (on, off—alternating each time the key is pressed).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download