简体   繁体   English

将字符串传递到SendInput()(C ++)

[英]Passing a string into SendInput() (C++)

Due To The Inconvenience, I've moved to C# for this project, no further comments needed 由于不便,我已将此项目移至C#,无需进一步评论

I've encountered an issue during the development of a C++ tidbit, which sends keystrokes based on user input. 在C ++花絮的开发过程中遇到了一个问题,该花絮根据用户输入发送击键。

Upon trying to send the actual keystrokes, I am greeted with an error. 尝试发送实际的击键后,我遇到了一个错误。

<error-type> message

I have posted a code snippet down below. 我在下面发布了一个代码段。 Any help is very much appreciated. 很感谢任何形式的帮助。

/*Code snippet from program that handles actual keypresses*/
string message;
getline(cin, message);

SendInput(message);

Look at documentation for SendInput 查看有关SendInput文档

You have to setup the INPUT structure, then pass array of INPUT . 您必须设置INPUT结构,然后传递INPUT数组。

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

int main()
{
    std::wstring msg = L"ΨΦΩ, ελη, ABC, abc, 123";
    //or std::string msg = "ABCD - abcd - 1234";

    std::vector<INPUT> vec;
    for(auto ch : msg)
    {
        INPUT input = { 0 };
        input.type = INPUT_KEYBOARD;
        input.ki.dwFlags = KEYEVENTF_UNICODE;
        input.ki.wScan = ch;
        vec.push_back(input);

        input.ki.dwFlags |= KEYEVENTF_KEYUP;
        vec.push_back(input);
    }

    //Find a notepad window or another window for send
    HWND hwnd = FindWindow("Notepad", 0);
    if (hwnd)
        SetForegroundWindow(hwnd);
    else
        std::cout << "no window!\n";

    SendInput(vec.size(), vec.data(), sizeof(INPUT));
    return 0;
}

Note that ANSI is deprecated in Windows. 请注意,Windows不推荐使用ANSI。 This code with std::string works only for ASCII characters. 带有std::string代码仅适用于ASCII字符。 For UNICODE compatibility use std::wstring 为了实现UNICODE兼容性,请使用std::wstring

Check this out: SendInput() Keyboard letters C/C++ 检查一下: SendInput()键盘字母C / C ++

You can't really just pass a entire string to it. 您不能真正将整个字符串传递给它。

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

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