0

Due To The Inconvenience, I've moved to C# for this project, no further comments needed

I've encountered an issue during the development of a C++ tidbit, which sends keystrokes based on user input.

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);
Carson
  • 6,105
  • 2
  • 37
  • 45
Koi
  • 87
  • 1
  • 9

2 Answers2

4

Look at documentation for SendInput

You have to setup the INPUT structure, then pass array of 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. This code with std::string works only for ASCII characters. For UNICODE compatibility use std::wstring

Barmak Shemirani
  • 30,904
  • 6
  • 40
  • 77
  • 1
    Note that `KEYEVENTF_UNICODE` expects UTF-16 input, and separate `INPUT` down/up pairs for UTF-16 surrogate pairs. If you need to send non-ASCII strings, you need to convert them to this format. – Remy Lebeau Mar 27 '18 at 03:57
  • @RemyLebeau I got ASCII and ANSI confused again. I think the answer is corrected now. – Barmak Shemirani Mar 27 '18 at 04:20
  • Thank you for your response. However, I now get the following errors: "'input' was not declared in this scope' and 'ch' does not name a type" – Koi Mar 27 '18 at 04:30
  • 1
    @Koi are you using C++11 or later? If not, then change the [range-based `for` loop](http://en.cppreference.com/w/cpp/language/range-for) into a normal `for` loop: `for(size_t i = 0; i < msg.size(); ++i) { ... input.ki.wScan = (WORD) msg[i]; ... }` – Remy Lebeau Mar 27 '18 at 05:23
0

Check this out: SendInput() Keyboard letters C/C++

You can't really just pass a entire string to it.

Yu Hua Guo
  • 36
  • 4