繁体   English   中英

INPUT / vector数组不适用于SendInput

[英]Array of INPUT / vector doesn't work with SendInput

所以我正在尝试使用SendInput来同时发送多个按键/按键释放。 数组和向量具有正确的信息,但由于某种原因,它只是没有按任何东西。 为什么?

我尝试从数组和向量中选择一个元素,并使用SendInput按下/释放键,它工作正常。

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

class movement
{
public:
    std::vector<INPUT> inputs;

    void Key(std::vector<INPUT> INPUTkeys)
    {
        INPUT * inputs = new INPUT[INPUTkeys.size()];

        for (int i = 0; i < INPUTkeys.size(); i++)
            inputs[i] = INPUTkeys.at(i);

        SendInput(INPUTkeys.size(), inputs, sizeof(inputs));

        delete[] inputs;
    }

    void prepareInput(INPUT &input, int key, bool down)
    {
        input.type = INPUT_KEYBOARD;
        input.ki.dwExtraInfo = NULL;
        input.ki.time = NULL;
        input.ki.wScan = NULL;
        input.ki.wVk = key;

        if (down)
            input.ki.dwFlags = 0;
        else
            input.ki.dwFlags = KEYEVENTF_KEYUP;
    }
};

movement oMovement;

void main()
{
    while (!GetAsyncKeyState(VK_SPACE))
        Sleep(1);

    std::vector<INPUT> inputs;

    INPUT input;

    oMovement.prepareInput(input, 'U', true);
    inputs.push_back(input);
    oMovement.prepareInput(input, 'S', true);
    inputs.push_back(input);
    oMovement.prepareInput(input, 'X', true);
    inputs.push_back(input);

    oMovement.Key(inputs);
    inputs.clear();

    oMovement.prepareInput(input, 'U', false);
    inputs.push_back(input);
    oMovement.prepareInput(input, 'S', false);
    inputs.push_back(input);
    oMovement.prepareInput(input, 'X', false);
    inputs.push_back(input);

    oMovement.Key(inputs);
    inputs.clear();

    system("pause");
}

您将指针的大小作为第三个参数传递给SendInput而它应该是INPUT结构的大小。 您还应检查结果(至少在调试模式下):

void Key(std::vector<INPUT> & INPUTkeys) // pass by reference to prevent copying
{
   ::UINT const sent_events_count
   {
       SendInput
       (
           static_cast<::UINT>(INPUTkeys.size())
       ,   INPUTkeys.data()
       ,   sizeof ::INTPUT
       )
   };
   assert(INPUTkeys.size() == sent_events_count);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM