I have searched the internet for a good system for emulating keypresses in C++.
I want to send a string to another program but as far as I can see the GenerateKey function can only send one at a time. I created code to break a string down and send each letter individually but sometimes the number of a specific letter in the alphabet is sent instead of the letter itself. (e.g. I enter “h” the computer spits out “8”)
How can I fix this and is there a better way to do it? Thank you!
#include <windows.h>
#include<iostream>
#include <winable.h>
#include <fstream>
#include<time.h>
#include<string>
using namespace std;
void GenerateKey(int vk, BOOL bExtended) {
KEYBDINPUT kb = {0};
INPUT Input = {0};
/* Generate a "key down" */
if (bExtended) { kb.dwFlags = KEYEVENTF_EXTENDEDKEY; }
kb.wVk = vk;
Input.type = INPUT_KEYBOARD;
Input.ki = kb;
SendInput(1, &Input, sizeof(Input));
/* Generate a "key up" */
ZeroMemory(&kb, sizeof(KEYBDINPUT));
ZeroMemory(&Input, sizeof(INPUT));
kb.dwFlags = KEYEVENTF_KEYUP;
if (bExtended) { kb.dwFlags |= KEYEVENTF_EXTENDEDKEY; }
kb.wVk = vk;
Input.type = INPUT_KEYBOARD;
Input.ki = kb;
SendInput(1, &Input, sizeof(Input));
return;
}
int main() {
SetConsoleTitle( "sendkeys" );
string sentence;
while (1){
cin>>sentence;
char letter;
int track = 0;
while(sentence[track] != '\0') {
cout<<sentence[track];
letter = sentence[track];
GenerateKey(letter, FALSE);
track++;
}
}
}
This sort of approach is really complicated (you have to manage state of SHIFT, CONTROL, and ALT, convert special characters to ALT+0xyz combos) and if the user changes keyboard focus in the process, keys can go to the wrong window.
Using
SendMessage(WM_SETTEXT)orSendMessage(EM_REPLACESEL)you could send a whole string at once to a particular window.