c++ - 使用 SendInput 函数模拟输入

标签 c++ windows winapi

下面的程序没有做任何事情,尽管预计会模拟每秒按“a”和“b”。为什么它不起作用?

#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;
}

最后的错误是

ERROR_NOACCESS

998 (0x3E6)

Invalid access to memory location.

但我不知道是什么原因造成的。

最佳答案

尝试

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

并检查返回值是否为非零。事实上,它应该等于发送的输入数,在本例中为 4。

如果被另一个线程或 UIPI ( User Interface Privilege Isolation ) 阻塞,该函数可能会失败

为避免其他问题,您可能需要检查当前键盘状态以及 SendInput 添加到输入流,而在运行时按下其他键可能会干扰它。

出于好奇,您要模拟什么 Action ? “伪造”用户对任何应用程序的输入通常不是一种非常优雅的做法。

关于c++ - 使用 SendInput 函数模拟输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11908262/

相关文章:

winapi - 为什么自定义窗口过程停止处理窗口消息?

c++ - 在 Windows 10 上尝试获取默认 Web 浏览器路径失败

c++ - 什么是 SCARY 迭代器?

c++ - 如何使用 errorno 和 _get_errno?

windows - 从 DOS/Windows 批处理文件运行 Sybase SQL 命令

windows - 有没有像PeekMessage这样不处理消息的函数?

c - WinAPI 命名管道位置

c++ - 移动后是否需要重置 std::list?

c++ - 我在编程这个 SUVAT 时做错了什么

C++ COM口的打开、读写