dsh-quiet-windows 0.0.0-stage → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,707 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """quietwin —— 把 GUI 窗口停在所有显示器之外,再用 UI Automation 操作它。
4
+
5
+ 设计约束(都是实测出来的,别改):
6
+ * 进程必须 DPI-aware,否则 175% 缩放下 PrintWindow 只截到左上角一块。
7
+ * 窗口必须保持 visible(不是最小化、不是 SW_HIDE):最小化后 DWM 不合成、
8
+ UIA 子树取不到。所以做法是 "先隐藏启动 -> 摆到屏幕外 -> SW_SHOWNOACTIVATE"。
9
+ * 屏幕外坐标取所有显示器并集之外,负方向,留 200px 余量。
10
+ * 不要把窗口搬到别的虚拟桌面:一旦它成为前台,Windows 会把你切过去。
11
+ * 动作前后记住/还原前台窗口,否则会把用户的键盘焦点抢到离屏窗口里。
12
+
13
+ 子命令:launch / list / shot / tree / act / close / state
14
+ 输出统一 JSON(--json)或人读文本。
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import argparse
19
+ import json
20
+ import os
21
+ import re
22
+ import shutil
23
+ import subprocess
24
+ import sys
25
+ import tempfile
26
+ import time
27
+
28
+ import ctypes
29
+ import win32api
30
+ import win32con
31
+ import win32gui
32
+ import win32process
33
+
34
+ BROWSERS = ("msedge.exe", "chrome.exe", "brave.exe", "firefox.exe", "thorium.exe")
35
+ MARGIN = 200
36
+ DWMWA_CLOAKED = 14
37
+ # 浏览器的临时 profile 全放这里;每次启动顺手清掉过期的,免得 %TEMP% 越滚越大。
38
+ PROFILE_ROOT = os.path.join(tempfile.gettempdir(), "dsh-quiet-profiles")
39
+ PROFILE_MAX_AGE_HOURS = 6.0
40
+
41
+
42
+ def sweep_profiles(max_age_hours: float = PROFILE_MAX_AGE_HOURS) -> int:
43
+ removed = 0
44
+ try:
45
+ if not os.path.isdir(PROFILE_ROOT):
46
+ return 0
47
+ cutoff = time.time() - max_age_hours * 3600
48
+ for entry in os.scandir(PROFILE_ROOT):
49
+ try:
50
+ if entry.is_dir() and entry.stat().st_mtime < cutoff:
51
+ shutil.rmtree(entry.path, ignore_errors=True)
52
+ removed += 1
53
+ except Exception:
54
+ continue
55
+ except Exception:
56
+ pass
57
+ return removed
58
+
59
+
60
+ # ---------------------------------------------------------------- win32 helpers
61
+ def dpi_aware() -> None:
62
+ try:
63
+ ctypes.windll.user32.SetProcessDpiAwarenessContext(ctypes.c_void_p(-4)) # PER_MONITOR_AWARE_V2
64
+ except Exception:
65
+ try:
66
+ ctypes.windll.shcore.SetProcessDpiAwareness(2)
67
+ except Exception:
68
+ pass
69
+
70
+
71
+ def monitors() -> list[tuple[int, int, int, int]]:
72
+ """所有显示器的矩形(物理像素,调用方必须已 DPI-aware)。"""
73
+ try:
74
+ import win32api
75
+
76
+ return [tuple(m[2]) for m in win32api.EnumDisplayMonitors()]
77
+ except Exception:
78
+ return [(
79
+ win32gui.GetSystemMetrics(76), win32gui.GetSystemMetrics(77),
80
+ win32gui.GetSystemMetrics(76) + win32gui.GetSystemMetrics(78),
81
+ win32gui.GetSystemMetrics(77) + win32gui.GetSystemMetrics(79),
82
+ )]
83
+
84
+
85
+ def offscreen_origin(width: int, height: int) -> tuple[int, int]:
86
+ """一块完全落在所有显示器之外的矩形左上角。"""
87
+ left = min(m[0] for m in monitors())
88
+ top = min(m[1] for m in monitors())
89
+ return left - width - MARGIN, top - height - MARGIN
90
+
91
+
92
+ def pids_of_image(name: str) -> set[int]:
93
+ import ctypes.wintypes as wt
94
+
95
+ class PROCESSENTRY32(ctypes.Structure):
96
+ _fields_ = [
97
+ ("dwSize", wt.DWORD), ("cntUsage", wt.DWORD), ("th32ProcessID", wt.DWORD),
98
+ ("th32DefaultHeapID", ctypes.POINTER(ctypes.c_ulong)), ("th32ModuleID", wt.DWORD),
99
+ ("cntThreads", wt.DWORD), ("th32ParentProcessID", wt.DWORD),
100
+ ("pcPriClassBase", ctypes.c_long), ("dwFlags", wt.DWORD),
101
+ ("szExeFile", ctypes.c_char * 260),
102
+ ]
103
+
104
+ snap = ctypes.windll.kernel32.CreateToolhelp32Snapshot(2, 0)
105
+ ent = PROCESSENTRY32()
106
+ ent.dwSize = ctypes.sizeof(PROCESSENTRY32)
107
+ pids: set[int] = set()
108
+ ok = ctypes.windll.kernel32.Process32First(snap, ctypes.byref(ent))
109
+ while ok:
110
+ if ent.szExeFile.decode(errors="ignore").lower() == name.lower():
111
+ pids.add(ent.th32ProcessID)
112
+ ok = ctypes.windll.kernel32.Process32Next(snap, ctypes.byref(ent))
113
+ ctypes.windll.kernel32.CloseHandle(snap)
114
+ return pids
115
+
116
+
117
+ def top_windows(pids: set[int] | None = None) -> list[int]:
118
+ out: list[int] = []
119
+
120
+ def cb(h, _):
121
+ if not win32gui.IsWindow(h) or win32gui.GetParent(h) != 0:
122
+ return True
123
+ if pids is not None:
124
+ _, pid = win32process.GetWindowThreadProcessId(h)
125
+ if pid not in pids:
126
+ return True
127
+ out.append(h)
128
+ return True
129
+
130
+ win32gui.EnumWindows(cb, None)
131
+ return out
132
+
133
+
134
+ def park(hwnd: int, x: int, y: int, activate: bool = False) -> None:
135
+ flags = win32con.SWP_NOSIZE | win32con.SWP_NOZORDER
136
+ if not activate:
137
+ flags |= win32con.SWP_NOACTIVATE
138
+ win32gui.SetWindowPos(hwnd, 0, x, y, 0, 0, flags)
139
+
140
+
141
+ def is_offscreen(hwnd: int) -> bool:
142
+ l, t, r, b = win32gui.GetWindowRect(hwnd)
143
+ for ml, mt, mr, mb in monitors():
144
+ if r > ml and l < mr and b > mt and t < mb:
145
+ return False
146
+ return True
147
+
148
+
149
+ def cloaked(hwnd: int):
150
+ val = ctypes.c_int(0)
151
+ hr = ctypes.windll.dwmapi.DwmGetWindowAttribute(
152
+ hwnd, DWMWA_CLOAKED, ctypes.byref(val), ctypes.sizeof(val))
153
+ return val.value if hr == 0 else None
154
+
155
+
156
+ def no_activate(hwnd: int) -> bool:
157
+ """给屏幕外窗口加上 WS_EX_NOACTIVATE:它再也不会成为前台窗口。
158
+
159
+ UIA 的 SetValue 之类动作会让控件调用 SetFocus,把离屏窗口顶上前台,抢走用户的键盘焦点。
160
+ 加上这个样式后,窗口仍能被 UIA 读写,但永不激活。
161
+ """
162
+ try:
163
+ ex = win32gui.GetWindowLong(hwnd, win32con.GWL_EXSTYLE)
164
+ if ex & win32con.WS_EX_NOACTIVATE:
165
+ return True
166
+ win32gui.SetWindowLong(hwnd, win32con.GWL_EXSTYLE, ex | win32con.WS_EX_NOACTIVATE)
167
+ win32gui.SetWindowPos(
168
+ hwnd, 0, 0, 0, 0, 0,
169
+ win32con.SWP_NOMOVE | win32con.SWP_NOSIZE | win32con.SWP_NOZORDER
170
+ | win32con.SWP_NOACTIVATE | win32con.SWP_FRAMECHANGED,
171
+ )
172
+ return bool(win32gui.GetWindowLong(hwnd, win32con.GWL_EXSTYLE) & win32con.WS_EX_NOACTIVATE)
173
+ except Exception:
174
+ return False
175
+
176
+
177
+ def force_foreground(hwnd: int) -> bool:
178
+ """把前台还给 hwnd。
179
+
180
+ Windows 的前台锁会让后台进程的 SetForegroundWindow 直接失败(返回 0,不抛异常)。
181
+ 绕法:把自己挂到当前前台线程和目标线程的输入队列上,再调一次。
182
+ """
183
+ if not hwnd or not win32gui.IsWindow(hwnd):
184
+ return False
185
+ try:
186
+ if win32gui.GetForegroundWindow() == hwnd:
187
+ return True
188
+ cur = win32api.GetCurrentThreadId()
189
+ fg = win32gui.GetForegroundWindow()
190
+ fg_tid = win32process.GetWindowThreadProcessId(fg)[0] if fg else 0
191
+ tgt_tid = win32process.GetWindowThreadProcessId(hwnd)[0]
192
+ attached = []
193
+ for tid in (fg_tid, tgt_tid):
194
+ if tid and tid != cur:
195
+ try:
196
+ win32process.AttachThreadInput(cur, tid, True)
197
+ attached.append(tid)
198
+ except Exception:
199
+ pass
200
+ try:
201
+ win32gui.BringWindowToTop(hwnd)
202
+ win32gui.SetForegroundWindow(hwnd)
203
+ finally:
204
+ for tid in attached:
205
+ try:
206
+ win32process.AttachThreadInput(cur, tid, False)
207
+ except Exception:
208
+ pass
209
+ time.sleep(0.08)
210
+ return win32gui.GetForegroundWindow() == hwnd
211
+ except Exception:
212
+ return False
213
+
214
+
215
+ def describe(hwnd: int) -> dict:
216
+ try:
217
+ l, t, r, b = win32gui.GetWindowRect(hwnd)
218
+ return {
219
+ "hwnd": hwnd,
220
+ "pid": win32process.GetWindowThreadProcessId(hwnd)[1],
221
+ "title": win32gui.GetWindowText(hwnd),
222
+ "class": win32gui.GetClassName(hwnd),
223
+ "rect": [l, t, r, b],
224
+ "visible": bool(win32gui.IsWindowVisible(hwnd)),
225
+ "minimized": bool(win32gui.IsIconic(hwnd)),
226
+ # 最小化窗口的矩形是 (-32000,-32000),也在所有显示器之外 —— 那不是"安静窗口",
227
+ # 只是被最小化了,必须排除,否则列表里全是用户自己的程序。
228
+ "offscreen": bool(win32gui.IsIconic(hwnd)) is False and is_offscreen(hwnd),
229
+ "cloaked": cloaked(hwnd),
230
+ }
231
+ except Exception as exc: # window died
232
+ return {"hwnd": hwnd, "error": f"{type(exc).__name__}: {exc}"}
233
+
234
+
235
+ def verify_pid(hwnd: int, expect: int | None) -> dict | None:
236
+ """句柄会被系统复用:动手前确认它还是当初那个进程的窗口。"""
237
+ if not expect:
238
+ return None
239
+ try:
240
+ actual = win32process.GetWindowThreadProcessId(hwnd)[1]
241
+ except Exception as exc:
242
+ return {"ok": False, "hwnd": hwnd, "error": f"窗口已不存在:{type(exc).__name__}: {exc}"}
243
+ if actual != expect:
244
+ return {"ok": False, "hwnd": hwnd,
245
+ "error": f"句柄已失效或被复用(期望 pid {expect},实际 {actual});"
246
+ f"请重新 quiet_windows 拿一个新的 hwnd"}
247
+ return None
248
+
249
+
250
+ # ------------------------------------------------------------------- capture
251
+ def shot(hwnd: int, out: str) -> dict:
252
+ """截窗口画面。PrintWindow 失败就不落盘 —— 半黑的图比"没有图"更容易骗到模型。"""
253
+ import win32ui
254
+ from PIL import Image
255
+
256
+ l, t, r, b = win32gui.GetWindowRect(hwnd)
257
+ w, h = r - l, b - t
258
+ if w <= 0 or h <= 0:
259
+ return {"ok": False, "error": "窗口没有可截取区域(可能已最小化)", "rect": [l, t, r, b]}
260
+
261
+ hdc = win32gui.GetWindowDC(hwnd)
262
+ src = mem = bmp = None
263
+ try:
264
+ src = win32ui.CreateDCFromHandle(hdc)
265
+ mem = src.CreateCompatibleDC()
266
+ bmp = win32ui.CreateBitmap()
267
+ bmp.CreateCompatibleBitmap(src, w, h)
268
+ mem.SelectObject(bmp)
269
+ ok = ctypes.windll.user32.PrintWindow(hwnd, mem.GetSafeHdc(), 2) # PW_RENDERFULLCONTENT
270
+ if not ok:
271
+ return {"ok": False, "hwnd": hwnd,
272
+ "error": "PrintWindow 返回失败;这个窗口可能不响应 WM_PRINT(硬件合成/受保护内容)",
273
+ "rect": [l, t, r, b]}
274
+ info = bmp.GetInfo()
275
+ img = Image.frombuffer("RGB", (info["bmWidth"], info["bmHeight"]),
276
+ bmp.GetBitmapBits(True), "raw", "BGRX", 0, 1)
277
+ gray = img.convert("L")
278
+ uniq = len(gray.getcolors(maxcolors=1 << 18) or [])
279
+ extrema = gray.getextrema()
280
+ os.makedirs(os.path.dirname(os.path.abspath(out)) or ".", exist_ok=True)
281
+ img.save(out)
282
+ return {
283
+ "ok": True, "path": os.path.abspath(out), "hwnd": hwnd,
284
+ "width": img.width, "height": img.height,
285
+ "unique_gray": uniq, "range": list(extrema),
286
+ # 纯色/黑图 => 这个应用在屏幕外不画,应降级
287
+ "looks_blank": uniq <= 3 or (extrema[1] - extrema[0] < 8),
288
+ }
289
+ finally:
290
+ try:
291
+ if bmp is not None:
292
+ win32gui.DeleteObject(bmp.GetHandle())
293
+ except Exception:
294
+ pass
295
+ try:
296
+ if mem is not None:
297
+ mem.DeleteDC()
298
+ except Exception:
299
+ pass
300
+ try:
301
+ if src is not None:
302
+ src.DeleteDC()
303
+ except Exception:
304
+ pass
305
+ try:
306
+ win32gui.ReleaseDC(hwnd, hdc)
307
+ except Exception:
308
+ pass
309
+
310
+
311
+ # ---------------------------------------------------------------- uia helpers
312
+ def uia_root(hwnd: int):
313
+ import uiautomation as auto
314
+
315
+ return auto.ControlFromHandle(hwnd)
316
+
317
+
318
+ def walk(ctrl, depth: int, out: list, path: str = "0") -> None:
319
+ if depth < 0:
320
+ return
321
+ try:
322
+ kids = ctrl.GetChildren()
323
+ except Exception:
324
+ return
325
+ for i, k in enumerate(kids):
326
+ p = f"{path}.{i}"
327
+ try:
328
+ rect = k.BoundingRectangle
329
+ item = {
330
+ "path": p,
331
+ "type": k.ControlTypeName,
332
+ "name": k.Name,
333
+ "class": k.ClassName,
334
+ "auto_id": getattr(k, "AutomationId", "") or "",
335
+ "rect": [rect.left, rect.top, rect.right, rect.bottom],
336
+ }
337
+ pats = []
338
+ for name in ("InvokePattern", "ValuePattern", "SelectionItemPattern",
339
+ "TogglePattern", "ExpandCollapsePattern", "TextPattern"):
340
+ try:
341
+ if name == "ValuePattern" and k.ControlTypeName not in ("EditControl", "ComboBoxControl"):
342
+ continue
343
+ if getattr(k, f"Get{name}")().__class__ and True:
344
+ pats.append(name[:-7].lower())
345
+ except Exception:
346
+ continue
347
+ item["patterns"] = sorted(set(pats))
348
+ out.append(item)
349
+ except Exception:
350
+ continue
351
+ walk(k, depth - 1, out, p)
352
+
353
+
354
+ def find(ctrl, budget: int = 6000, max_depth: int = 14, **want):
355
+ """在树里按 name/class/auto_id/type 找一个控件,返回 (control, path)。
356
+
357
+ 遍历**所有**子节点(不再限定几种容器类型)——按钮、CustomControl 底下也常挂着内容,
358
+ 只钻"容器白名单"会漏。规模靠 budget(节点预算)与 max_depth 兜住。
359
+ """
360
+ if not any(want.get(k) for k in ("name", "exact_name", "class", "auto_id", "type")):
361
+ return None, None
362
+ queue = [(ctrl, "0", 0)]
363
+ seen = 0
364
+ while queue and seen < budget:
365
+ cur, path, depth = queue.pop(0)
366
+ seen += 1
367
+ try:
368
+ kids = cur.GetChildren()
369
+ except Exception:
370
+ continue
371
+ for i, k in enumerate(kids):
372
+ p = f"{path}.{i}"
373
+ try:
374
+ match = True
375
+ if want.get("name") and want["name"] not in k.Name:
376
+ match = False
377
+ if want.get("exact_name") and want["exact_name"] != k.Name:
378
+ match = False
379
+ if want.get("class") and want["class"] not in k.ClassName:
380
+ match = False
381
+ if want.get("auto_id") and want["auto_id"] != getattr(k, "AutomationId", ""):
382
+ match = False
383
+ if want.get("type") and want["type"] != k.ControlTypeName:
384
+ match = False
385
+ except Exception:
386
+ continue
387
+ if match:
388
+ return k, p
389
+ if depth + 1 < max_depth:
390
+ queue.append((k, p, depth + 1))
391
+ return None, None
392
+
393
+
394
+ def act(hwnd: int, op: str, value: str | None, selector: dict) -> dict:
395
+ import uiautomation as auto # noqa: F401
396
+
397
+ fg_before = win32gui.GetForegroundWindow()
398
+ root = uia_root(hwnd)
399
+ target, path = find(root, **selector)
400
+ if target is None:
401
+ return {"ok": False, "error": "control not found", "selector": selector,
402
+ "foreground_restored": False}
403
+ try:
404
+ if op == "invoke":
405
+ target.GetInvokePattern().Invoke()
406
+ elif op == "set":
407
+ target.GetValuePattern().SetValue(value or "")
408
+ elif op == "select":
409
+ target.GetSelectionItemPattern().Select()
410
+ elif op == "toggle":
411
+ target.GetTogglePattern().Toggle()
412
+ elif op == "expand":
413
+ target.GetExpandCollapsePattern().Expand()
414
+ elif op == "collapse":
415
+ target.GetExpandCollapsePattern().Collapse()
416
+ elif op == "focus":
417
+ target.SetFocus()
418
+ else:
419
+ return {"ok": False, "error": f"unknown op {op}"}
420
+ res = {"ok": True, "op": op, "path": path, "target": target.Name,
421
+ "type": target.ControlTypeName}
422
+ except Exception as exc:
423
+ return {"ok": False, "error": f"{type(exc).__name__}: {exc}", "path": path}
424
+
425
+ time.sleep(0.25)
426
+ # 焦点护栏:把前台还给用户
427
+ restored = False
428
+ fg_after = win32gui.GetForegroundWindow()
429
+ if fg_after != fg_before and fg_before:
430
+ restored = force_foreground(fg_before)
431
+ res["foreground_before"] = fg_before
432
+ res["foreground_after"] = fg_after
433
+ res["foreground_restored"] = restored
434
+ return res
435
+
436
+
437
+ # --------------------------------------------------------------------- launch
438
+ def launch(exe: str, args: list[str], width: int, height: int, timeout: float,
439
+ title_re: str | None, keep_hidden: bool, allow_activate: bool = False,
440
+ isolate: bool = True, keep_on_failure: bool = False) -> dict:
441
+ name = os.path.basename(exe).lower()
442
+ fg0 = win32gui.GetForegroundWindow()
443
+ ox, oy = offscreen_origin(width, height)
444
+ before = pids_of_image(name)
445
+
446
+ extra = list(args)
447
+ isolated_profile = None
448
+ # 浏览器默认开独立 profile:否则已运行的浏览器会把新窗口收进旧进程,新进程立刻退出。
449
+ # 那时我们既不知道窗口属于谁,close --kill 还可能把用户整个浏览器带走。
450
+ if name in BROWSERS and isolate and not any(
451
+ a.lower().startswith("--user-data-dir") for a in extra):
452
+ sweep_profiles()
453
+ isolated_profile = os.path.join(
454
+ PROFILE_ROOT, f"{name.replace('.exe', '')}-{time.time_ns()}")
455
+ extra = [f"--user-data-dir={isolated_profile}", "--no-first-run",
456
+ "--no-default-browser-check", *extra]
457
+
458
+ if name in BROWSERS:
459
+ # Chromium 支持在创建时就定位置,能真正做到零闪现
460
+ cmd = [exe, f"--window-position={ox},{oy}", f"--window-size={width},{height}",
461
+ "--disable-backgrounding-occluded-windows", "--disable-renderer-backgrounding",
462
+ "--disable-features=CalculateNativeWinOcclusion,IntensiveWakeUpThrottling", *extra]
463
+ else:
464
+ cmd = [exe, *extra]
465
+
466
+ si = subprocess.STARTUPINFO()
467
+ si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
468
+ si.wShowWindow = win32con.SW_HIDE
469
+ proc = subprocess.Popen(cmd, startupinfo=si, close_fds=True)
470
+
471
+ def cleanup(reason: str) -> dict:
472
+ """启动失败时收拾现场:不留下看不见的进程和临时 profile。"""
473
+ killed = False
474
+ if not keep_on_failure:
475
+ try:
476
+ subprocess.run(["taskkill", "/T", "/F", "/PID", str(proc.pid)],
477
+ capture_output=True)
478
+ killed = True
479
+ except Exception:
480
+ killed = False
481
+ if isolated_profile:
482
+ shutil.rmtree(isolated_profile, ignore_errors=True)
483
+ return {"ok": False, "error": reason, "proc_pid": proc.pid,
484
+ "cleaned": killed, "isolated_profile": isolated_profile,
485
+ "launched": cmd}
486
+
487
+ deadline = time.time() + timeout
488
+ hwnd = None
489
+ flashed = False
490
+ while time.time() < deadline:
491
+ fresh = pids_of_image(name) - before
492
+ if proc.poll() is not None and not fresh:
493
+ return cleanup(
494
+ "启动的进程立即退出且没有新进程出现:该程序很可能把窗口交给了已运行的实例。"
495
+ "浏览器请使用独立 --user-data-dir(本插件默认已开),或先关掉旧实例再试。")
496
+ new = fresh | {proc.pid}
497
+ cands = [h for h in top_windows(new)
498
+ if win32gui.GetWindowText(h) and win32gui.GetClassName(h) != "IME"]
499
+ if title_re:
500
+ cands = [h for h in cands if re.search(title_re, win32gui.GetWindowText(h))]
501
+ if cands:
502
+ hwnd = max(cands, key=lambda h: len(win32gui.GetWindowText(h)))
503
+ if win32gui.IsWindowVisible(hwnd) and not is_offscreen(hwnd):
504
+ flashed = True # 真的出现在用户屏幕上了,立刻挪走
505
+ l2, t2, r2, b2 = win32gui.GetWindowRect(hwnd)
506
+ park(hwnd, *offscreen_origin(max(r2 - l2, 1), max(b2 - t2, 1)))
507
+ break
508
+ time.sleep(0.15)
509
+
510
+ if hwnd is None:
511
+ return cleanup(f"等待窗口超时({timeout:.0f} 秒)")
512
+
513
+ # 摆好位置再显示;期间反复检查,绝不让它停在屏幕内。
514
+ # 注意:必须按窗口"真实尺寸"重算屏幕外原点 —— 有些程序不理会请求的宽高
515
+ # (charmap 固定 1051x875),只挪位置会有一角露在屏幕里。
516
+ for _ in range(20):
517
+ l, t, r, b = win32gui.GetWindowRect(hwnd)
518
+ w, h = max(r - l, 1), max(b - t, 1)
519
+ ox, oy = offscreen_origin(w, h)
520
+ if not is_offscreen(hwnd) or (r - l) != width or (b - t) != height:
521
+ if win32gui.IsWindowVisible(hwnd) and not is_offscreen(hwnd):
522
+ flashed = True
523
+ win32gui.SetWindowPos(
524
+ hwnd, 0, ox, oy, width, height,
525
+ win32con.SWP_NOZORDER | win32con.SWP_NOACTIVATE)
526
+ if not keep_hidden:
527
+ # 先上 NOACTIVATE 再显示,连"首帧抢一下前台"都不给它。
528
+ if not allow_activate:
529
+ no_activate(hwnd)
530
+ win32gui.ShowWindow(hwnd, win32con.SW_SHOWNOACTIVATE)
531
+ time.sleep(0.15)
532
+
533
+ info = describe(hwnd)
534
+ window_pid = info.get("pid")
535
+ mismatch = window_pid != proc.pid
536
+ # 永不激活:否则 UIA 的 SetFocus / 控件刷新会把离屏窗口顶上前台,抢走键盘焦点。
537
+ info["no_activate"] = False if allow_activate else no_activate(hwnd)
538
+ # 焦点护栏:首次 ShowWindow 仍可能把新窗口顶上前台;发现就还回去。
539
+ focus_stolen = False
540
+ try:
541
+ focus_stolen = bool(fg0) and win32gui.GetForegroundWindow() != fg0
542
+ if focus_stolen and win32gui.IsWindow(fg0):
543
+ force_foreground(fg0)
544
+ except Exception:
545
+ pass
546
+ info.update({
547
+ "ok": True,
548
+ # pid 一律是「窗口所属进程」,启动器进程单独放 proc_pid —— 两者可能不同。
549
+ "pid": window_pid,
550
+ "window_pid": window_pid,
551
+ "proc_pid": proc.pid,
552
+ "process_mismatch": mismatch,
553
+ "shared_process": mismatch,
554
+ "isolated_profile": isolated_profile,
555
+ "flashed": flashed,
556
+ "focus_stolen": focus_stolen,
557
+ "park_origin": [ox, oy],
558
+ "launched": cmd,
559
+ })
560
+ return info
561
+
562
+
563
+ # ----------------------------------------------------------------------- main
564
+ def main() -> int:
565
+ dpi_aware()
566
+ # --json 允许出现在任意位置(subparser 之前或之后),先摘掉再解析。
567
+ raw = sys.argv[1:]
568
+ want_json = "--json" in raw
569
+ raw = [x for x in raw if x != "--json"]
570
+
571
+ ap = argparse.ArgumentParser(prog="quietwin")
572
+ sub = ap.add_subparsers(dest="cmd", required=True)
573
+
574
+ p = sub.add_parser("launch")
575
+ p.add_argument("--exe", required=True)
576
+ p.add_argument("--arg", action="append", default=[])
577
+ # 参数里常带 '-' 开头(Chromium 开关就是),逐项 --arg 会被 argparse 当成选项,
578
+ # 所以再给一个 JSON 数组入口。
579
+ p.add_argument("--argv-json", default=None)
580
+ p.add_argument("--width", type=int, default=1280)
581
+ p.add_argument("--height", type=int, default=860)
582
+ p.add_argument("--timeout", type=float, default=25.0)
583
+ p.add_argument("--title", default=None)
584
+ p.add_argument("--keep-hidden", action="store_true")
585
+ p.add_argument("--allow-activate", action="store_true")
586
+ p.add_argument("--no-isolate", action="store_true",
587
+ help="浏览器不启用独立 profile(默认启用;关掉后可能寄生到已运行的浏览器里)")
588
+ p.add_argument("--keep-on-failure", action="store_true",
589
+ help="启动失败时不结束已拉起的进程,留给你自己排查")
590
+
591
+ sub.add_parser("list")
592
+
593
+ p = sub.add_parser("shot")
594
+ p.add_argument("--hwnd", type=int, required=True)
595
+ p.add_argument("--out", required=True)
596
+ p.add_argument("--expect-pid", type=int, default=None)
597
+
598
+ p = sub.add_parser("tree")
599
+ p.add_argument("--hwnd", type=int, required=True)
600
+ p.add_argument("--depth", type=int, default=4)
601
+ p.add_argument("--expect-pid", type=int, default=None)
602
+
603
+ p = sub.add_parser("act")
604
+ p.add_argument("--hwnd", type=int, required=True)
605
+ p.add_argument("--op", required=True,
606
+ choices=["invoke", "set", "select", "toggle", "expand", "collapse", "focus"])
607
+ p.add_argument("--value", default=None)
608
+ p.add_argument("--name", default=None)
609
+ p.add_argument("--exact-name", default=None)
610
+ p.add_argument("--class", dest="class_", default=None)
611
+ p.add_argument("--auto-id", default=None)
612
+ p.add_argument("--type", dest="type_", default=None)
613
+ p.add_argument("--expect-pid", type=int, default=None)
614
+
615
+ p = sub.add_parser("close")
616
+ p.add_argument("--hwnd", type=int, required=True)
617
+ p.add_argument("--kill", action="store_true")
618
+ p.add_argument("--expect-pid", type=int, default=None)
619
+
620
+ sub.add_parser("state")
621
+
622
+ a = ap.parse_args(raw)
623
+
624
+ if a.cmd == "launch":
625
+ extra = list(a.arg or [])
626
+ if a.argv_json:
627
+ try:
628
+ decoded = json.loads(a.argv_json)
629
+ if isinstance(decoded, list):
630
+ extra.extend(str(x) for x in decoded)
631
+ except Exception as exc:
632
+ print(json.dumps({"ok": False, "error": f"--argv-json 不是合法 JSON 数组: {exc}"},
633
+ ensure_ascii=False))
634
+ return 2
635
+ res = launch(a.exe, extra, a.width, a.height, a.timeout, a.title,
636
+ a.keep_hidden, a.allow_activate, not a.no_isolate, a.keep_on_failure)
637
+ elif a.cmd == "list":
638
+ wins = [describe(h) for h in top_windows()
639
+ if win32gui.GetWindowText(h) and win32gui.IsWindowVisible(h)]
640
+ res = {"ok": True, "monitors": monitors(),
641
+ "dpi": ctypes.windll.user32.GetDpiForSystem(),
642
+ "foreground": describe(win32gui.GetForegroundWindow()),
643
+ "offscreen": [w for w in wins if w.get("offscreen")],
644
+ "count": len(wins)}
645
+ elif a.cmd == "shot":
646
+ res = verify_pid(a.hwnd, a.expect_pid) or shot(a.hwnd, a.out)
647
+ elif a.cmd == "tree":
648
+ res = verify_pid(a.hwnd, a.expect_pid)
649
+ if res is None:
650
+ root = uia_root(a.hwnd)
651
+ if root is None:
652
+ res = {"ok": False, "error": "no UIA element for hwnd"}
653
+ else:
654
+ items: list = []
655
+ walk(root, a.depth, items)
656
+ res = {"ok": True, "hwnd": a.hwnd, "root": {"name": root.Name,
657
+ "class": root.ClassName, "type": root.ControlTypeName},
658
+ "count": len(items), "items": items}
659
+ elif a.cmd == "act":
660
+ res = verify_pid(a.hwnd, a.expect_pid)
661
+ if res is None:
662
+ selector = {"name": a.name, "exact_name": a.exact_name, "class": a.class_,
663
+ "auto_id": a.auto_id, "type": a.type_}
664
+ res = act(a.hwnd, a.op, a.value, {k: v for k, v in selector.items() if v})
665
+ elif a.cmd == "close":
666
+ res = verify_pid(a.hwnd, a.expect_pid)
667
+ if res is None:
668
+ info = describe(a.hwnd)
669
+ try:
670
+ win32gui.PostMessage(a.hwnd, win32con.WM_CLOSE, 0, 0)
671
+ time.sleep(1.0)
672
+ alive = win32gui.IsWindow(a.hwnd)
673
+ killed = False
674
+ # 只按「窗口所属进程」杀,而且必须是我们确认过的那一个;
675
+ # 共享进程(寄生到用户已开的浏览器)默认不动进程,只关窗口。
676
+ if alive and a.kill and info.get("pid"):
677
+ subprocess.run(["taskkill", "/T", "/F", "/PID", str(info["pid"])],
678
+ capture_output=True)
679
+ killed = True
680
+ time.sleep(0.5)
681
+ alive = win32gui.IsWindow(a.hwnd)
682
+ res = {"ok": True, "closed": not alive, "killed": killed,
683
+ "window": info,
684
+ "hint": None if not alive else "窗口仍在;可加 kill=true,或手动处理该进程"}
685
+ except Exception as exc:
686
+ res = {"ok": False, "error": f"{type(exc).__name__}: {exc}"}
687
+ else: # state
688
+ res = {
689
+ "ok": True,
690
+ "monitors": monitors(),
691
+ "foreground": describe(win32gui.GetForegroundWindow()),
692
+ "cursor": list(win32gui.GetCursorPos()),
693
+ "offscreen_windows": [describe(h) for h in top_windows()
694
+ if win32gui.IsWindowVisible(h) and win32gui.GetWindowText(h)
695
+ and is_offscreen(h)],
696
+ "dpi": ctypes.windll.user32.GetDpiForSystem(),
697
+ }
698
+
699
+ if want_json:
700
+ print(json.dumps(res, ensure_ascii=False, indent=2))
701
+ else:
702
+ print(res)
703
+ return 0 if res.get("ok") else 1
704
+
705
+
706
+ if __name__ == "__main__":
707
+ sys.exit(main())