c++macroskeyboardbotssendinput

How to Simulate Holding Down a Key in C++


In a gaming macro bot that I'm working on, I'm trying to simulate walking forward.

This game is run through my Chrome browser. All I need this code to accomplish is to produce wwwwwwwwwwwwww in a Notepad window or something due to the key being held down.

To my knowledge, this is NOT a compatibility error, but a logical error.

Here's a bare-bones example of my road block:

#include <windows.h>

void keyPress(WORD keyCode) 
{
    INPUT input;
    input.type = INPUT_KEYBOARD;

    input.ki.wVk = keyCode;
    input.ki.dwFlags = 0;
    SendInput(1, &input, sizeof(input)); // Press key?

    Sleep(3000); // Key suppose to be held for 3 seconds but isnt??

    input.ki.dwFlags = KEYEVENTF_KEYUP;
    SendInput(1, &input, sizeof(input)); // Release key?
}

int main()
{
    keyPress(0x57); // 0x57 = W key code
    return 0;
}

SendInput() seemed like the function to use for key press simulation, but if I should be using something different, please share!


Solution

  • SOLUTION: Okay, through further experience with this, it seems the problem with my original code was the lack of KEYEVENTF_SCANCODE in my dwFlags. There seems to be a underlying relationship that requires the KEYEVENTF_SCANCODE flag in order to hold down an arrow key at least in Chrome, maybe systemwide. So here is the bare-bones solution:

    #include <windows.h>
    
    void keyPress(WORD keyCode)
    {
        INPUT input;
        input.type = INPUT_KEYBOARD;
        input.ki.wScan = keyCode;
        input.ki.dwFlags = KEYEVENTF_SCANCODE;
    
        SendInput(1, &input, sizeof(INPUT));
    }
    
    void keyRelease(WORD keyCode)
    {
        INPUT input;
        input.type = INPUT_KEYBOARD;
        input.ki.wScan = keyCode;
        input.ki.dwFlags = KEYEVENTF_SCANCODE | KEYEVENTF_KEYUP;
    
        SendInput(1, &input, sizeof(INPUT));
    }
    
    int main()
    {
        Sleep(5000); // pause time to open browser tab
        keyPress(0x24); // press key
        Sleep(1000); // hold key for x milliseconds
        keyRelease(0x24); // release key
        return 0;
    }
    

    I'm confused why the scan codes arent lining up with the ones provided by microsoft ("0x25" is down arrow instead of "0x28"?) so if someones got some insight for that, then that'd be great.

    SOLUTION EDIT: The reason why my keycodes weren't lining up was because I need to use scancodes. I had some dumb luck in that the game I am botting also uses IJKL as arrow keys so it appeared as though the codes were off set by a few numbers when in actuality it was pressing letter keys the whole time. So basically all I need to do is use these scan codes to move: 0x17="I" 0x24="J" 0x25="K" 0x26="L"

    I hope this helps someone as lost as I was (:

    also, pro tip, code macro bots in python, its much less of a headache. I abandoned my c++ code and got my code running on python in 2 evenings