Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
557 views
in Technique[技术] by (71.8m points)

c++ - 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!!!
";
    
    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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...