挣扎于 SendInput()

Struggling with SendInput()

我想通过模仿键盘将 4 位数字的所有可能组合注入到不同的程序(例如记事本)中,但我终究无法弄清楚如何使用 SendInput() 函数,或者如果有更好的选择。

string code;
for (int digit1 = startThousand; digit1 < 10; digit1++){
    for (int digit2 = 0; digit2 < 10; digit2++){
        for (int digit3 = 0; digit3 < 10; digit3++){
            for (int digit4 = 0; digit4 < 10; digit4++){

            code = (std::to_string(digit1)+std::to_string(digit2)+std::to_string(digit3)+std::to_string(digit4));
                    //generating the 4 digit codes and outputting the final code into a single variable
            cout << code << "\n";
                    //printing the code
            SendInput(code, ???, sizeof(code))
                    //sending the code into a different program

}}}}

SendInput 不接受字符串作为参数。

  Sendinput(cInputs, pInputs, cbSize);

//cInputs = number of structures in the pInputs array..
//pInputs = a pointer to a INPUT structure which contains info about your mouse/key event. 
//cbSize  = the size of the structure. Tip! use sizeof();
//Step 1.
//Declare a KEYBDINPUT struct and set appropriate values to each variable.
//See MSDN...
//
//Step 2.
//Declare a INPUT structure.
//Set type: INPUT_KEYBOARD. then set "yourinputstruct".ki equal to your keybdinput struct
//
//Step 3:
//Use Sendinput function! Sendinput(1,&yourinputstruct, sizeof(yourinutstruct));

有关虚拟键码列表,请参阅 MSDN。 https://docs.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes

这是我编写的函数,它可能仍需要一些改进,但我认为它会满足您的要求!至少它对我在 cmd 和记事本中输入有用...阅读 msdn 或让我评论是否难以理解!

只需传入一个虚拟键码作为第一个参数,如果它是扩展键则为 true,否则为 false!

void KeyPress(unsigned short VK, bool ExtendedKey)
{
    KEYBDINPUT  KeyDown = { 0 };
    KEYBDINPUT  KeyUp = { 0 };
    INPUT Input[2] = { 0 };

    //KeyDown...
    KeyDown.wVk = VK;
    KeyDown.wScan = 0;
    KeyDown.time = 10;
    KeyDown.dwFlags = 0;
    KeyDown.dwExtraInfo = 0;

    if (ExtendedKey == true)
    {
        KeyDown.wVk = VK;
        KeyDown.wScan = 0;
        KeyDown.time = 1000;
        KeyDown.dwFlags = KEYEVENTF_EXTENDEDKEY;
        KeyDown.dwExtraInfo = 0;
    }

    //KeyUp...
    KeyUp.wVk = VK;
    KeyUp.wScan = 0;
    KeyUp.time = 10;
    KeyUp.dwFlags = KEYEVENTF_KEYUP;
    KeyUp.dwExtraInfo = 0;

    if (ExtendedKey == true)
    {
        KeyUp.wVk = VK;
        KeyUp.wScan = 0;
        KeyUp.time = 10;
        KeyUp.dwFlags = KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP;
        KeyUp.dwExtraInfo = 0;
    }
    //Setup Input...
    Input[0].type = INPUT_KEYBOARD;
    Input[0].ki = KeyDown;

    Input[1].type = INPUT_KEYBOARD;
    Input[1].ki = KeyUp;

    //Click and Release!
    SendInput(1, &Input[0], sizeof(Input[0]));
    SendInput(1, &Input[1], sizeof(Input[1]));
}