-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathagent_computer.cpp
More file actions
567 lines (530 loc) · 21.2 KB
/
Copy pathagent_computer.cpp
File metadata and controls
567 lines (530 loc) · 21.2 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
// agent_computer.cpp —— 电脑控制(截图/OCR/鼠标/键盘/窗口/进程/启动程序)
#include "agent_internal.h"
// ============================================================
// 电脑控制工具(截图 / OCR / 鼠标 / 键盘 / 窗口 / 进程)
// ============================================================
// ---- GDI+ 截图 ----
static ULONG_PTR g_gdiplusToken = 0;
static bool g_gdiplusReady = false;
bool ensureGdiplus()
{
if (g_gdiplusReady) return true;
Gdiplus::GdiplusStartupInput in;
if (Gdiplus::GdiplusStartup(&g_gdiplusToken, &in, nullptr) != Gdiplus::Ok) return false;
g_gdiplusReady = true;
return true;
}
int getPngEncoderClsid(CLSID *clsid)
{
UINT num = 0, size = 0;
Gdiplus::GetImageEncodersSize(&num, &size);
if (size == 0) return -1;
std::vector<BYTE> buf(size);
Gdiplus::ImageCodecInfo *info = reinterpret_cast<Gdiplus::ImageCodecInfo *>(buf.data());
Gdiplus::GetImageEncoders(num, size, info);
for (UINT i = 0; i < num; i++)
{
if (wcscmp(info[i].MimeType, L"image/png") == 0)
{
*clsid = info[i].Clsid;
return (int)i;
}
}
return -1;
}
// 截取屏幕区域(x,y,w,h 为物理像素坐标;w/h<=0 表示整个虚拟屏幕),保存 PNG,返回 "OK 路径"。
// originX/originY 回传实际抓取原点:多显示器下虚拟屏原点可能为负,调用方做坐标换算时必须用它。
std::string captureScreenToPng(const std::string &filePath, int x, int y, int w, int h,
int *originX, int *originY)
{
if (!ensureGdiplus()) return "Tool Error: GDI+ 初始化失败";
HDC screenDc = GetDC(nullptr);
if (!screenDc) return "Tool Error: 无法获取屏幕 DC";
int vx = GetSystemMetrics(SM_XVIRTUALSCREEN);
int vy = GetSystemMetrics(SM_YVIRTUALSCREEN);
int sw = GetSystemMetrics(SM_CXVIRTUALSCREEN);
int sh = GetSystemMetrics(SM_CYVIRTUALSCREEN);
if (w <= 0 || h <= 0) { x = vx; y = vy; w = sw; h = sh; }
if (originX) *originX = x;
if (originY) *originY = y;
HDC memDc = CreateCompatibleDC(screenDc);
if (!memDc)
{
ReleaseDC(nullptr, screenDc);
return "Tool Error: 无法创建内存 DC";
}
HBITMAP hbmp = CreateCompatibleBitmap(screenDc, w, h);
if (!hbmp)
{
DeleteDC(memDc);
ReleaseDC(nullptr, screenDc);
return "Tool Error: 创建位图失败";
}
HGDIOBJ old = SelectObject(memDc, hbmp);
BOOL blitOk = BitBlt(memDc, 0, 0, w, h, screenDc, x, y, SRCCOPY);
SelectObject(memDc, old);
DeleteDC(memDc);
ReleaseDC(nullptr, screenDc);
if (!blitOk)
{
DeleteObject(hbmp);
return "Tool Error: 屏幕抓取失败(BitBlt)";
}
CLSID pngClsid;
if (getPngEncoderClsid(&pngClsid) < 0) { DeleteObject(hbmp); return "Tool Error: 未找到 PNG 编码器"; }
Gdiplus::Status st = Gdiplus::Ok;
{
// Gdiplus::Bitmap 不接管 HBITMAP 的所有权:必须在 Bitmap 析构之后才能 DeleteObject,
// 否则是 GDI+ 契约上的未定义用法。
Gdiplus::Bitmap bmp(hbmp, nullptr);
st = bmp.Save(utf8ToWide(filePath).c_str(), &pngClsid, nullptr);
}
DeleteObject(hbmp);
if (st != Gdiplus::Ok) return "Tool Error: 保存 PNG 失败 (code " + std::to_string((int)st) + ")";
return "OK " + filePath;
}
static int g_tempCounter = 0;
std::string makeTempFilePath(const char *ext)
{
char tmpDir[MAX_PATH];
if (!getTempDir(tmpDir, MAX_PATH))
return ""; // 调用方必须判空;原先不检查返回值,会用未初始化缓冲拼路径
std::string name = "ycode_" + std::to_string(GetCurrentProcessId()) + "_" +
std::to_string(GetTickCount()) + "_" + std::to_string(g_tempCounter++) + ext;
return std::string(tmpDir) + name;
}
// 运行 ycode_ocr.ps1 识别 pngPath 中的文字,完整 JSON 写入 jsonPath
std::string runOcrScript(const std::string &pngPath, const std::string &jsonPath)
{
std::string scriptPath;
const char *envScript = std::getenv("YCODE_OCR_SCRIPT");
if (envScript && *envScript) scriptPath = envScript;
if (scriptPath.empty())
{
std::string dir = moduleDirUtf8();
std::string cand1 = dir + "\\scripts\\ycode_ocr.ps1";
std::string cand2 = dir + "\\ycode_ocr.ps1";
// 路径来自可执行文件目录,可能是 UTF-8 的中文路径 → 用宽字符 API 判断存在性
if (GetFileAttributesW(utf8ToWide(cand1).c_str()) != INVALID_FILE_ATTRIBUTES) scriptPath = cand1;
else if (GetFileAttributesW(utf8ToWide(cand2).c_str()) != INVALID_FILE_ATTRIBUTES) scriptPath = cand2;
}
if (scriptPath.empty())
return "Tool Error: 找不到 ycode_ocr.ps1(可设置环境变量 YCODE_OCR_SCRIPT 指定路径)";
std::string cmd = "powershell -NoProfile -ExecutionPolicy Bypass -File \"" + scriptPath + "\" \"" + pngPath + "\" \"" + jsonPath + "\"";
std::string out = executeShellCommand(cmd, 90000);
if (out.find("OK ") == 0) return "";
return out.empty() ? "Tool Error: OCR 脚本无输出" : out;
}
// 截屏并 OCR,返回给模型的 JSON(坐标为屏幕物理像素坐标)
std::string screenOcrJson(int x, int y, int w, int h)
{
static std::string lastOcrPng; // 只保留最近一次的临时 PNG,避免 %TEMP% 无限增长
std::string pngPath = makeTempFilePath(".png");
std::string jsonPath = makeTempFilePath(".json");
if (pngPath.empty() || jsonPath.empty())
return "Tool Error: 无法获取系统临时目录";
int originX = 0, originY = 0;
std::string err = captureScreenToPng(pngPath, x, y, w, h, &originX, &originY);
if (err.rfind("OK ", 0) != 0) return err;
if (!lastOcrPng.empty() && lastOcrPng != pngPath)
{
DeleteFileA(lastOcrPng.c_str());
lastOcrPng.clear();
}
lastOcrPng = pngPath;
std::string ocrErr = runOcrScript(pngPath, jsonPath);
if (!ocrErr.empty()) return ocrErr;
std::string content = readFile(jsonPath);
DeleteFileA(jsonPath.c_str());
if (content.empty() || content.find("\"error\"") != std::string::npos)
return "Tool Error: OCR 失败或识别不到文字";
try
{
json j = json::parse(content);
// 截取区域时的原点偏移 -> 绝对屏幕坐标。
// 必须用实际抓取原点:整屏模式下它为虚拟屏原点(多显示器时可能为负),
// 原先用调用方传入的 x/y(此时是 0)判断,副屏布局下坐标整体偏移。
if (originX != 0 || originY != 0)
{
if (j.contains("lines") && j["lines"].is_array())
{
for (auto &line : j["lines"])
{
if (line.contains("x")) line["x"] = line["x"].get<int>() + originX;
if (line.contains("y")) line["y"] = line["y"].get<int>() + originY;
}
}
}
// 裁剪体积:最多 80 行、行文本最长 200 字符、去掉 words
std::vector<json> kept;
int count = 0;
if (j.contains("lines") && j["lines"].is_array())
{
for (auto &line : j["lines"])
{
if (count >= 80) break;
json slim;
slim["text"] = line.value("text", std::string(""));
slim["x"] = line.value("x", 0);
slim["y"] = line.value("y", 0);
slim["w"] = line.value("w", 0);
slim["h"] = line.value("h", 0);
kept.push_back(slim);
count++;
}
}
j["lines"] = kept;
j["line_count"] = count;
j["screenshot"] = pngPath;
return j.dump();
}
catch (...)
{
return "Tool Error: OCR 结果解析失败";
}
}
// ---- 窗口枚举 ----
struct WindowEntry
{
std::wstring title;
std::wstring cls;
int x, y, w, h;
bool visible;
bool focused;
};
BOOL CALLBACK enumWindowsProc(HWND hwnd, LPARAM lparam)
{
auto *vec = reinterpret_cast<std::vector<WindowEntry> *>(lparam);
if (vec->size() >= 200) return FALSE;
wchar_t title[512] = {0}, cls[256] = {0};
GetWindowTextW(hwnd, title, 512);
GetClassNameW(hwnd, cls, 256);
if (wcslen(title) == 0) return TRUE;
RECT r;
GetWindowRect(hwnd, &r);
if (r.right - r.left <= 0 || r.bottom - r.top <= 0) return TRUE;
WindowEntry e;
e.title = title;
e.cls = cls;
e.x = r.left;
e.y = r.top;
e.w = r.right - r.left;
e.h = r.bottom - r.top;
e.visible = IsWindowVisible(hwnd) != FALSE;
e.focused = (hwnd == GetForegroundWindow());
vec->push_back(e);
return TRUE;
}
json listWindowsJson()
{
std::vector<WindowEntry> vec;
EnumWindows(enumWindowsProc, reinterpret_cast<LPARAM>(&vec));
json arr = json::array();
for (const auto &e : vec)
{
json item;
item["title"] = wstringToUtf8(e.title);
item["class"] = wstringToUtf8(e.cls);
item["x"] = e.x;
item["y"] = e.y;
item["w"] = e.w;
item["h"] = e.h;
item["visible"] = e.visible;
item["focused"] = e.focused;
arr.push_back(item);
}
return arr;
}
HWND findWindowByTitleSubstr(const std::string &substr)
{
std::string needle = substr;
std::transform(needle.begin(), needle.end(), needle.begin(),
[](unsigned char c) { return static_cast<char>(std::tolower(c)); });
std::vector<WindowEntry> vec;
EnumWindows(enumWindowsProc, reinterpret_cast<LPARAM>(&vec));
for (const auto &e : vec)
{
std::string lower = wstringToUtf8(e.title);
std::transform(lower.begin(), lower.end(), lower.begin(),
[](unsigned char c) { return static_cast<char>(std::tolower(c)); });
if (lower.find(needle) != std::string::npos)
return FindWindowW(nullptr, e.title.c_str());
}
return nullptr;
}
// ---- 进程枚举 ----
json listProcessesJson()
{
json arr = json::array();
HANDLE snap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (snap == INVALID_HANDLE_VALUE) return arr;
PROCESSENTRY32W pe;
pe.dwSize = sizeof(pe);
int count = 0;
if (Process32FirstW(snap, &pe))
{
do
{
if (count >= 300) break;
json item;
item["pid"] = static_cast<int>(pe.th32ProcessID);
item["name"] = wstringToUtf8(pe.szExeFile);
arr.push_back(item);
count++;
} while (Process32NextW(snap, &pe));
}
CloseHandle(snap);
return arr;
}
json cursorPosJson()
{
POINT p;
GetCursorPos(&p);
json j;
j["x"] = p.x;
j["y"] = p.y;
return j;
}
// ---- 鼠标 ----
void mouseMoveAbsolute(int x, int y)
{
int vx = GetSystemMetrics(SM_XVIRTUALSCREEN);
int vy = GetSystemMetrics(SM_YVIRTUALSCREEN);
int sw = GetSystemMetrics(SM_CXVIRTUALSCREEN);
int sh = GetSystemMetrics(SM_CYVIRTUALSCREEN);
if (sw <= 0 || sh <= 0) return;
long nx = static_cast<long>((double)(x - vx) * 65535.0 / sw);
long ny = static_cast<long>((double)(y - vy) * 65535.0 / sh);
nx = nx < 0 ? 0 : (nx > 65535 ? 65535 : nx);
ny = ny < 0 ? 0 : (ny > 65535 ? 65535 : ny);
INPUT in = {};
in.type = INPUT_MOUSE;
in.mi.dx = nx;
in.mi.dy = ny;
in.mi.dwFlags = MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE;
SendInput(1, &in, sizeof(INPUT));
}
// ============================================================
// 全局输入锁:与 YiyangzaiBot 微信循环等任务共享命名互斥量,
// 电脑控制(鼠标/键盘)操作前必须获取,避免多任务抢鼠标打架。
// ============================================================
static HANDLE g_inputMutex = nullptr;
bool acquireInputLock(DWORD timeoutMs = 30000)
{
if (!g_inputMutex)
{
g_inputMutex = CreateMutexA(nullptr, FALSE, "Local\\YiyangzaiInputLock");
if (!g_inputMutex)
return false;
}
return WaitForSingleObject(g_inputMutex, timeoutMs) == WAIT_OBJECT_0;
}
void releaseInputLock()
{
if (g_inputMutex)
ReleaseMutex(g_inputMutex);
}
class InputLockGuard
{
public:
InputLockGuard() : ok(acquireInputLock()) {}
~InputLockGuard() { if (ok) releaseInputLock(); }
bool ok;
};
std::string mouseClickAt(int x, int y, const std::string &button, int clicks)
{
InputLockGuard guard;
if (!guard.ok)
return "Tool Error: 输入锁获取超时(其他任务正在使用鼠标键盘),请稍后重试";
mouseMoveAbsolute(x, y);
Sleep(60);
DWORD down = MOUSEEVENTF_LEFTDOWN, up = MOUSEEVENTF_LEFTUP;
std::string b = button;
std::transform(b.begin(), b.end(), b.begin(),
[](unsigned char c) { return static_cast<char>(std::tolower(c)); });
if (b == "right") { down = MOUSEEVENTF_RIGHTDOWN; up = MOUSEEVENTF_RIGHTUP; }
else if (b == "middle") { down = MOUSEEVENTF_MIDDLEDOWN; up = MOUSEEVENTF_MIDDLEUP; }
if (clicks <= 0) clicks = 1;
if (clicks > 5) clicks = 5;
for (int i = 0; i < clicks; i++)
{
INPUT in[2] = {};
in[0].type = INPUT_MOUSE;
in[0].mi.dwFlags = down;
in[1].type = INPUT_MOUSE;
in[1].mi.dwFlags = up;
SendInput(2, in, sizeof(INPUT));
if (clicks > 1) Sleep(60);
}
return "OK 已点击 (" + std::to_string(x) + ", " + std::to_string(y) + ") " + b + " x" + std::to_string(clicks);
}
std::string mouseMoveToTool(int x, int y)
{
InputLockGuard guard;
if (!guard.ok)
return "Tool Error: 输入锁获取超时(其他任务正在使用鼠标键盘),请稍后重试";
mouseMoveAbsolute(x, y);
return "OK 鼠标已移动到 (" + std::to_string(x) + ", " + std::to_string(y) + ")";
}
std::string mouseScrollTool(int delta, int x, int y)
{
InputLockGuard guard;
if (!guard.ok)
return "Tool Error: 输入锁获取超时(其他任务正在使用鼠标键盘),请稍后重试";
if (x >= 0 && y >= 0) mouseMoveAbsolute(x, y);
Sleep(50);
INPUT in = {};
in.type = INPUT_MOUSE;
in.mi.dwFlags = MOUSEEVENTF_WHEEL;
in.mi.mouseData = static_cast<DWORD>(delta);
SendInput(1, &in, sizeof(INPUT));
return "OK 滚轮滚动 delta=" + std::to_string(delta);
}
// ---- 键盘 ----
bool setClipboardTextUtf8(const std::string &text)
{
std::wstring wtext = utf8ToWide(text);
if (!OpenClipboard(nullptr)) return false;
EmptyClipboard();
size_t bytes = (wtext.size() + 1) * sizeof(wchar_t);
HGLOBAL hg = GlobalAlloc(GMEM_MOVEABLE, bytes);
if (!hg) { CloseClipboard(); return false; }
void *dst = GlobalLock(hg);
if (dst) { memcpy(dst, wtext.c_str(), bytes); GlobalUnlock(hg); }
if (SetClipboardData(CF_UNICODETEXT, hg) == nullptr) { GlobalFree(hg); CloseClipboard(); return false; }
CloseClipboard();
return true;
}
void sendVkKey(WORD vk, bool extended, bool down)
{
INPUT in = {};
in.type = INPUT_KEYBOARD;
in.ki.wVk = vk;
if (extended) in.ki.dwFlags |= KEYEVENTF_EXTENDEDKEY;
if (!down) in.ki.dwFlags |= KEYEVENTF_KEYUP;
SendInput(1, &in, sizeof(INPUT));
}
std::string keyboardTypeTextTool(const std::string &text)
{
InputLockGuard guard;
if (!guard.ok)
return "Tool Error: 输入锁获取超时(其他任务正在使用鼠标键盘),请稍后重试";
if (!setClipboardTextUtf8(text)) return "Tool Error: 无法写入剪贴板";
Sleep(80);
sendVkKey(VK_CONTROL, false, true);
sendVkKey('V', false, true);
sendVkKey('V', false, false);
sendVkKey(VK_CONTROL, false, false);
Sleep(150);
return "OK 已输入文本 (" + std::to_string(text.size()) + " 字符)";
}
bool parseKeyName(const std::string &token, KeySpec &out)
{
std::string t = token;
std::transform(t.begin(), t.end(), t.begin(),
[](unsigned char c) { return static_cast<char>(std::tolower(c)); });
if (t.size() == 1)
{
char c = static_cast<char>(std::tolower(t[0]));
if (c >= 'a' && c <= 'z') { out.vk = 'A' + (c - 'a'); out.extended = false; return true; }
if (c >= '0' && c <= '9') { out.vk = '0' + (c - '0'); out.extended = false; return true; }
SHORT sc = VkKeyScanW(static_cast<wchar_t>(static_cast<unsigned char>(t[0])));
if (sc != -1) { out.vk = static_cast<WORD>(sc & 0xFF); out.extended = false; return true; }
return false;
}
static const struct { const char *name; WORD vk; bool ext; } map[] = {
{"enter", VK_RETURN, false}, {"return", VK_RETURN, false}, {"tab", VK_TAB, false},
{"esc", VK_ESCAPE, false}, {"escape", VK_ESCAPE, false}, {"space", VK_SPACE, false},
{"backspace", VK_BACK, false}, {"bs", VK_BACK, false}, {"delete", VK_DELETE, true}, {"del", VK_DELETE, true},
{"insert", VK_INSERT, true}, {"ins", VK_INSERT, true}, {"home", VK_HOME, true}, {"end", VK_END, true},
{"pgup", VK_PRIOR, true}, {"pageup", VK_PRIOR, true}, {"pgdn", VK_NEXT, true}, {"pagedown", VK_NEXT, true},
{"up", VK_UP, true}, {"down", VK_DOWN, true}, {"left", VK_LEFT, true}, {"right", VK_RIGHT, true},
{"win", VK_LWIN, false}, {"lwin", VK_LWIN, false}, {"rwin", VK_RWIN, false},
{"ctrl", VK_CONTROL, false}, {"control", VK_CONTROL, false}, {"alt", VK_MENU, false}, {"shift", VK_SHIFT, false},
{"capslock", VK_CAPITAL, false}, {"printscreen", VK_SNAPSHOT, false}, {"prtsc", VK_SNAPSHOT, false},
{"pause", VK_PAUSE, false}, {"numlock", VK_NUMLOCK, false}, {"scrolllock", VK_SCROLL, false},
{"apps", VK_APPS, false}, {"menu", VK_APPS, false},
{"f1", VK_F1, false}, {"f2", VK_F2, false}, {"f3", VK_F3, false}, {"f4", VK_F4, false},
{"f5", VK_F5, false}, {"f6", VK_F6, false}, {"f7", VK_F7, false}, {"f8", VK_F8, false},
{"f9", VK_F9, false}, {"f10", VK_F10, false}, {"f11", VK_F11, false}, {"f12", VK_F12, false},
{"f13", VK_F13, false}, {"f14", VK_F14, false}, {"f15", VK_F15, false}, {"f16", VK_F16, false},
{"f17", VK_F17, false}, {"f18", VK_F18, false}, {"f19", VK_F19, false}, {"f20", VK_F20, false},
{"f21", VK_F21, false}, {"f22", VK_F22, false}, {"f23", VK_F23, false}, {"f24", VK_F24, false},
};
for (const auto &m : map)
if (t == m.name) { out.vk = m.vk; out.extended = m.ext; return true; }
return false;
}
std::string keyboardPressComboTool(const std::string &combo)
{
InputLockGuard guard;
if (!guard.ok)
return "Tool Error: 输入锁获取超时(其他任务正在使用鼠标键盘),请稍后重试";
std::vector<KeySpec> keys;
std::stringstream ss(combo);
std::string token;
while (std::getline(ss, token, '+'))
{
token.erase(0, token.find_first_not_of(" \t"));
token.erase(token.find_last_not_of(" \t") + 1);
if (token.empty()) continue;
KeySpec ks;
if (!parseKeyName(token, ks))
return "Tool Error: 无法识别的按键: " + token + "(可用 ctrl/alt/shift/win/enter/tab/esc/f1-f24/方向键等,用 + 连接)";
keys.push_back(ks);
}
if (keys.empty()) return "Tool Error: 按键组合为空";
auto isModifier = [](const KeySpec &k) {
return k.vk == VK_CONTROL || k.vk == VK_MENU || k.vk == VK_SHIFT || k.vk == VK_LWIN || k.vk == VK_RWIN;
};
for (const auto &k : keys)
if (isModifier(k)) sendVkKey(k.vk, k.extended, true);
Sleep(40);
// 依次按下所有非修饰键。原先循环里 break 只发最后一个,
// 多个非修饰键的组合(如 a+b)会被静默丢掉一个。
for (const auto &k : keys)
{
if (isModifier(k)) continue;
sendVkKey(k.vk, k.extended, true);
sendVkKey(k.vk, k.extended, false);
}
Sleep(40);
for (auto it = keys.rbegin(); it != keys.rend(); ++it)
if (isModifier(*it)) sendVkKey(it->vk, it->extended, false);
return "OK 已按键: " + combo;
}
// ---- 窗口操作 ----
std::string activateWindowTool(const std::string &title)
{
InputLockGuard guard;
if (!guard.ok)
return "Tool Error: 输入锁获取超时(其他任务正在使用鼠标键盘),请稍后重试";
if (title.empty()) return "Tool Error: title 不能为空";
HWND hwnd = findWindowByTitleSubstr(title);
if (!hwnd) return "Tool Error: 未找到标题包含 \"" + title + "\" 的窗口(可用 list_windows 查看当前窗口列表)";
if (IsIconic(hwnd)) ShowWindow(hwnd, SW_RESTORE);
SetForegroundWindow(hwnd);
if (GetForegroundWindow() != hwnd)
{
keybd_event(VK_MENU, 0, 0, 0);
keybd_event(VK_MENU, 0, KEYEVENTF_KEYUP, 0);
SetForegroundWindow(hwnd);
}
return "OK 已激活窗口: " + title;
}
std::string closeWindowTool(const std::string &title)
{
if (title.empty()) return "Tool Error: title 不能为空";
HWND hwnd = findWindowByTitleSubstr(title);
if (!hwnd) return "Tool Error: 未找到标题包含 \"" + title + "\" 的窗口";
PostMessage(hwnd, WM_CLOSE, 0, 0);
return "OK 已向窗口发送关闭请求: " + title;
}
std::string startAppTool(const std::string &target)
{
// target 是 UTF-8(可能含中文路径/中文应用名)→ 必须走宽字符 ShellExecuteW
HINSTANCE r = ShellExecuteW(nullptr, L"open", utf8ToWide(target).c_str(), nullptr, nullptr, SW_SHOWNORMAL);
if (reinterpret_cast<INT_PTR>(r) <= 32)
return "Tool Error: 启动失败 (code " + std::to_string(reinterpret_cast<INT_PTR>(r)) + ")";
return "OK 已启动: " + target;
}