-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkeyemitter.cpp
More file actions
75 lines (61 loc) · 2.18 KB
/
keyemitter.cpp
File metadata and controls
75 lines (61 loc) · 2.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include "keyemitter.h"
#include <vector>
#include <windows.h>
KeyEmitter::KeyEmitter(QObject *parent)
: QObject(parent) {}
void KeyEmitter::reset() {
lastText.clear();
}
void KeyEmitter::applyText(const QString &text) {
if (text == lastText)
return;
int prefix = 0;
const int minLen = qMin(text.size(), lastText.size());
while (prefix < minLen && text.at(prefix) == lastText.at(prefix))
++prefix;
const int toDelete = lastText.size() - prefix;
if (toDelete > 0)
sendBackspace(toDelete);
const QString toAdd = text.mid(prefix);
if (!toAdd.isEmpty())
sendUnicodeText(toAdd);
lastText = text;
}
void KeyEmitter::appendText(const QString &text) {
if (text.isEmpty())
return;
sendUnicodeText(text);
lastText += text;
}
void KeyEmitter::sendBackspace(int count) {
if (count <= 0)
return;
// Batch all backspace key events into a single SendInput call
std::vector<INPUT> inputs(static_cast<size_t>(count) * 2, INPUT{});
for (int i = 0; i < count; ++i) {
const size_t idx = static_cast<size_t>(i) * 2;
inputs[idx].type = INPUT_KEYBOARD;
inputs[idx].ki.wVk = VK_BACK;
inputs[idx + 1].type = INPUT_KEYBOARD;
inputs[idx + 1].ki.wVk = VK_BACK;
inputs[idx + 1].ki.dwFlags = KEYEVENTF_KEYUP;
}
SendInput(static_cast<UINT>(inputs.size()), inputs.data(), sizeof(INPUT));
}
void KeyEmitter::sendUnicodeText(const QString &text) {
if (text.isEmpty())
return;
// Batch all character key events into a single SendInput call
std::vector<INPUT> inputs(static_cast<size_t>(text.size()) * 2, INPUT{});
for (int i = 0; i < text.size(); ++i) {
const size_t idx = static_cast<size_t>(i) * 2;
const ushort unicode = text.at(i).unicode();
inputs[idx].type = INPUT_KEYBOARD;
inputs[idx].ki.wScan = unicode;
inputs[idx].ki.dwFlags = KEYEVENTF_UNICODE;
inputs[idx + 1].type = INPUT_KEYBOARD;
inputs[idx + 1].ki.wScan = unicode;
inputs[idx + 1].ki.dwFlags = KEYEVENTF_UNICODE | KEYEVENTF_KEYUP;
}
SendInput(static_cast<UINT>(inputs.size()), inputs.data(), sizeof(INPUT));
}