Reputation: 77
I would like to write a function that receives a char and presses it on the keyboard.
void pressKey(const char key){
INPUT ip;
ip.type = INPUT_KEYBOARD;
ip.ki.wScan = 0;
ip.ki.time = 0;
ip.ki.dwExtraInfo = 0;
ip.ki.wVk = //What to put here? (receives WORD of the hex value)
ip.ki.dwFlags = 0;
SendInput(1, &ip, sizeof(INPUT));
}
How can I press the key 'a' (for example) and press it using this method or any other method?
Upvotes: 0
Views: 424
Reputation: 596397
When simulating keyboard input for text, you should use the KEYEVENTF_UNICODE
flag to send Unicode characters as-is, use virtual key codes only for non-textual keys. And you need to send 2 input events per character, one event to press the key down, and one event to release it.
For example:
void pressKey(const char key){
INPUT ip[2] = {};
ip[0].type = INPUT_KEYBOARD;
ip[0].ki.wScan = key;
ip[0].ki. dwFlags = KEYEVENTF_UNICODE;
ip[1] = ip[0];
ip[1].ki.dwFlags |= KEYEVENTF_KEYUP;
SendInput(2, ip, sizeof(INPUT));
}
That being said, since this approach requires Unicode characters, if your key
will ever contain a non-ASCII character then you will need to first convert it to Unicode UTF-16, such as with MultiByteToWideChar()
or equivalent, and then you can send down/up events for each UTF-16 codeunit, as shown in this answer.
Upvotes: 1