1

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.

Community
  • 1
  • 1
0x6B6F77616C74
  • 2,559
  • 7
  • 38
  • 65
  • 1
    The first parameter to Sendinput is incorrect. – Raymond Chen Aug 10 '12 at 19:56
  • 1
    Also, the input.ki.dwFlags of your first INPUT may be random garbage from the stack, since INPUT input is declared, but not initialized to anything - you should set it to 0 explicitly, as you do in the third item. – BrendanMcK Aug 17 '12 at 09:52

1 Answers1

2

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.

AJG85
  • 15,849
  • 13
  • 42
  • 50