Warm tip: This article is reproduced from serverfault.com, please click

Using KeyPress in C++ from string input creates errors

发布于 2020-12-19 09:27:27

Solved: Check the void SendInputString( std::wstring &str) function in this answer

I am developing an executable in C++ which can be given a string as a command-line parameter and it will be typed emulating the keyboard; using keypresses.

In the format on command line:

{program name} {string to reproduce} {time between individual keypresses in ms}

This is my code:

#define WINVER 0x0500
#include <windows.h>

void chartype(char x , INPUT  &input, unsigned int pause_time){

    input.ki.wVk=VkKeyScanA(x);
    //Verifies character and allots the key to the keyboard 

    //cout<<x; //Old check code 


    Sleep(pause_time);
    
    SendInput(1,&input,sizeof(INPUT));
    //To send input  

    return;
}



int main(int argc , char** argv){
    //Initializing a GUI Keyboard Set 
    INPUT input;
    input.type=INPUT_KEYBOARD;

    //Assigning Input Variables
    string str = argv[1];
    size_t n = str.size();
    unsigned int pause_time = stoi(argv[2]);
 
    //Sending individual string characters 
    for(size_t i =0 ; i<n ; ++i){

        chartype(str[i] , input , pause_time);

    }

    //Shutting Keyboard
    input.ki.dwFlags=KEYEVENTF_KEYUP;
    SendInput(1, &input,sizeof(INPUT));
    
    return 0; 
}

However, the string is not exactly executed. For example if I input the string PASS_INPUT, it renders pass-input. Also, the output is sensitive to whether or not Caps Lock is on or not.

I assume it is happening because it only kind of emulates pressing the specific key on the keyboard, and thus assumes a default value, however I want it to present exact outputs, such as %9Xa{ to give %9Xa{ and not 59xa[ which is happening presently.

I am sorry if I could not frame the question well enough. I am new to this keyboard emulation, and am not able to exactly understand what to do.

I would like to know what modification should be made to render the string as expected.

Questioner
Aniruddh Anna
Viewed
0
Aniruddh Anna 2020-12-19 20:20:07

Can use the function SendInputString( std::wstring &str) from this answer