1

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); 
6
  • @FredLarson Thank you for the answer, but I get another error in return. In this case, "too few arguments in function call" Commented Mar 27, 2018 at 2:07
  • 2
    You'll need to read the docs. It's not that simple, I'm afraid. Commented Mar 27, 2018 at 2:11
  • The error literally says "<error-type> message" ? Commented Mar 27, 2018 at 2:23
  • @immibis Indeed. Commented Mar 27, 2018 at 2:32
  • 1
    Way up there with the classic "Syntax error on line 42" Commented Mar 27, 2018 at 2:49

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

4 Comments

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.
@RemyLebeau I got ASCII and ANSI confused again. I think the answer is corrected now.
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 are you using C++11 or later? If not, then change the range-based for loop into a normal for loop: for(size_t i = 0; i < msg.size(); ++i) { ... input.ki.wScan = (WORD) msg[i]; ... }
0

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

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

1 Comment

That's correct but the examples send one INPUT at a time, it's supposed to send an array.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.