0x6B6F77616C74
0x6B6F77616C74

Reputation: 2629

Simulating input using the SendInput function

The following program didn't do anything, athough had been expected to simulate pressing "a" and "b" for each second. Why it doesn't work?

#include <Windows.h>
#include <iostream>

using namespace std;

const int INPUTS = 4;

int main()
{
    INPUT inputArray[INPUTS];
    
    INPUT input;

    input.type = INPUT_KEYBOARD;

    //Press 'a' key
    input.ki.wVk = 0x41;
    input.ki.wScan = MapVirtualKey(0x41,MAPVK_VK_TO_VSC);
    inputArray[0] = input;
    
    //Release 'a' key
    input.ki.dwFlags = KEYEVENTF_KEYUP;
    inputArray[1] = input;
    

    //Press 'b' key
    input.ki.dwFlags = 0;
    input.ki.wVk = 0x42;
    input.ki.wScan = MapVirtualKey(0x42,MAPVK_VK_TO_VSC);
    inputArray[2] = input;

    //Release 'b' key
    input.ki.dwFlags = KEYEVENTF_KEYUP;
    inputArray[3] = input;

    Sleep(5000);

    std::cout<<"GO!!!\n";
    
    for(int i=0; i<100; i++)
    {
        SendInput(sizeof(inputArray),inputArray,sizeof(INPUT));
        Sleep(1000); //Don't remove!
    }       
        
    std::cout<<GetLastError()<<std::endl;

    system("Pause");
    return 0;
}

The last error is

ERROR_NOACCESS

998 (0x3E6)

Invalid access to memory location.

but I don't know what caused it.

Upvotes: 1

Views: 2681

Answers (1)

AJG85
AJG85

Reputation: 16197

Try

SendInput(INPUTS, inputArray, sizeof(INPUT));

and check that the return value is non-zero. In fact, it should equal to the number of inputs sent, in this case 4.

The function may fail if it is blocked by another thread or UIPI (User Interface Privilege Isolation)

To avoid other problems you may want to check the current keyboard state as well as SendInput adds to the input stream and other keys being pressed while this is running could interfere with it.

Out of curiosity what action are you trying to simulate? It's generally not a very graceful practice to "fake" user input to any application.

Upvotes: 2

Related Questions