"""Small Win32 helpers over ctypes (windows, processes, capture). Windows only.""" from __future__ import annotations import ctypes import hashlib import json import os import subprocess from ctypes import wintypes user32 = ctypes.WinDLL("user32", use_last_error=True) kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) gdi32 = ctypes.WinDLL("gdi32", use_last_error=True) psapi = ctypes.WinDLL("psapi", use_last_error=True) dwmapi = ctypes.WinDLL("dwmapi") shell32 = ctypes.WinDLL("shell32") GWL_STYLE, GWL_EXSTYLE = -16, -20 WS_CAPTION, WS_THICKFRAME, WS_POPUP = 0x00C00000, 0x00040000, 0x80000000 WS_EX_TOOLWINDOW, WS_EX_APPWINDOW, WS_EX_TOPMOST = 0x00000080, 0x00040000, 0x00000008 SW_HIDE, SW_SHOWNOACTIVATE = 0, 4 SWP_NOSIZE, SWP_NOMOVE, SWP_NOACTIVATE, SWP_FRAMECHANGED = 0x1, 0x2, 0x10, 0x20 HWND_BOTTOM = wintypes.HWND(1) PW_RENDERFULLCONTENT = 2 PROCESS_QUERY_LIMITED_INFORMATION = 0x1000 # Every handle argument must be declared: without argtypes ctypes passes a # Python int as a 32-bit C int, and a 64-bit HWND then fails with # "OverflowError: int too long to convert" (seen on a real Windows 11 run). _H, _D, _U, _I = wintypes.HWND, wintypes.DWORD, wintypes.UINT, ctypes.c_int for _fn, _args, _res in ( (user32.GetWindowLongPtrW, [_H, _I], ctypes.c_ssize_t), (user32.SetWindowLongPtrW, [_H, _I, ctypes.c_ssize_t], ctypes.c_ssize_t), (user32.GetForegroundWindow, [], _H), (user32.GetWindowThreadProcessId, [_H, ctypes.POINTER(_D)], _D), (user32.GetWindowTextLengthW, [_H], _I), (user32.GetWindowTextW, [_H, wintypes.LPWSTR, _I], _I), (user32.GetClassNameW, [_H, wintypes.LPWSTR, _I], _I), (user32.GetWindowRect, [_H, ctypes.POINTER(wintypes.RECT)], wintypes.BOOL), (user32.IsWindowVisible, [_H], wintypes.BOOL), (user32.IsIconic, [_H], wintypes.BOOL), (user32.MonitorFromWindow, [_H, _D], wintypes.HMONITOR), (user32.GetMonitorInfoW, [wintypes.HMONITOR, ctypes.c_void_p], wintypes.BOOL), (user32.GetWindowDC, [_H], wintypes.HDC), (user32.ReleaseDC, [_H, wintypes.HDC], _I), (user32.PrintWindow, [_H, wintypes.HDC, _U], wintypes.BOOL), (user32.ShowWindow, [_H, _I], wintypes.BOOL), (user32.SetWindowPos, [_H, _H, _I, _I, _I, _I, _U], wintypes.BOOL), (gdi32.CreateCompatibleDC, [wintypes.HDC], wintypes.HDC), (gdi32.CreateCompatibleBitmap, [wintypes.HDC, _I, _I], wintypes.HBITMAP), (gdi32.SelectObject, [wintypes.HDC, wintypes.HGDIOBJ], wintypes.HGDIOBJ), (gdi32.GetDIBits, [wintypes.HDC, wintypes.HBITMAP, _U, _U, ctypes.c_void_p, ctypes.c_void_p, _U], _I), (gdi32.DeleteObject, [wintypes.HGDIOBJ], wintypes.BOOL), (gdi32.DeleteDC, [wintypes.HDC], wintypes.BOOL), (kernel32.OpenProcess, [_D, wintypes.BOOL, _D], wintypes.HANDLE), (kernel32.QueryFullProcessImageNameW, [wintypes.HANDLE, _D, wintypes.LPWSTR, ctypes.POINTER(_D)], wintypes.BOOL), (kernel32.CloseHandle, [wintypes.HANDLE], wintypes.BOOL), (psapi.EnumProcesses, [ctypes.POINTER(_D), _D, ctypes.POINTER(_D)], wintypes.BOOL), (dwmapi.DwmGetWindowAttribute, [_H, _D, ctypes.c_void_p, _D], ctypes.c_long), ): _fn.argtypes, _fn.restype = _args, _res def dpi_aware() -> None: try: user32.SetProcessDpiAwarenessContext(ctypes.c_void_p(-4)) # per-monitor v2 except Exception: try: ctypes.windll.shcore.SetProcessDpiAwareness(2) except Exception: pass class MONITORINFO(ctypes.Structure): _fields_ = [("cbSize", wintypes.DWORD), ("rcMonitor", wintypes.RECT), ("rcWork", wintypes.RECT), ("dwFlags", wintypes.DWORD)] def _rect(r: wintypes.RECT) -> list[int]: return [r.left, r.top, r.right, r.bottom] def window_info(hwnd: int) -> dict: pid = wintypes.DWORD() user32.GetWindowThreadProcessId(hwnd, ctypes.byref(pid)) n = user32.GetWindowTextLengthW(hwnd) buf = ctypes.create_unicode_buffer(n + 1) user32.GetWindowTextW(hwnd, buf, n + 1) cls = ctypes.create_unicode_buffer(256) user32.GetClassNameW(hwnd, cls, 256) r = wintypes.RECT() user32.GetWindowRect(hwnd, ctypes.byref(r)) cloaked = ctypes.c_int(0) dwmapi.DwmGetWindowAttribute(wintypes.HWND(hwnd), 14, ctypes.byref(cloaked), ctypes.sizeof(cloaked)) return {"hwnd": int(hwnd), "pid": pid.value, "title": buf.value, "class": cls.value, "rect": _rect(r), "visible": bool(user32.IsWindowVisible(hwnd)), "minimized": bool(user32.IsIconic(hwnd)), "cloaked": bool(cloaked.value), "style": user32.GetWindowLongPtrW(hwnd, GWL_STYLE) & 0xFFFFFFFF, "exstyle": user32.GetWindowLongPtrW(hwnd, GWL_EXSTYLE) & 0xFFFFFFFF} def top_windows(visible_only: bool = True) -> list[dict]: found: list[dict] = [] proc = ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM) def cb(hwnd, _lp): if not visible_only or user32.IsWindowVisible(hwnd): found.append(window_info(hwnd)) return True user32.EnumWindows(proc(cb), 0) return found def monitor_rect(hwnd: int) -> list[int]: hmon = user32.MonitorFromWindow(wintypes.HWND(hwnd), 2) mi = MONITORINFO() mi.cbSize = ctypes.sizeof(MONITORINFO) user32.GetMonitorInfoW(hmon, ctypes.byref(mi)) return _rect(mi.rcMonitor) def proc_path(pid: int) -> str | None: h = kernel32.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, False, pid) if not h: return None try: buf = ctypes.create_unicode_buffer(1024) size = wintypes.DWORD(1024) if kernel32.QueryFullProcessImageNameW(h, 0, buf, ctypes.byref(size)): return buf.value return None finally: kernel32.CloseHandle(h) def processes() -> dict[int, str]: """pid -> exe name (lower case).""" arr = (wintypes.DWORD * 8192)() needed = wintypes.DWORD() psapi.EnumProcesses(arr, ctypes.sizeof(arr), ctypes.byref(needed)) out = {} for pid in arr[: needed.value // ctypes.sizeof(wintypes.DWORD)]: if pid: p = proc_path(pid) if p: out[pid] = os.path.basename(p).lower() return out def foreground() -> dict | None: h = user32.GetForegroundWindow() return window_info(h) if h else None def notification_state() -> str: """SHQueryUserNotificationState: 'd3d_fullscreen' is exclusive fullscreen D3D.""" v = ctypes.c_int(0) shell32.SHQueryUserNotificationState(ctypes.byref(v)) return {1: "not_present", 2: "busy", 3: "d3d_fullscreen", 4: "presentation_mode", 5: "accepts_notifications", 6: "quiet_time", 7: "app"}.get(v.value, str(v.value)) def capture_hash(hwnd: int) -> tuple[str | None, bool]: """PrintWindow(PW_RENDERFULLCONTENT) -> (md5 of pixels, all_black). Works for covered windows.""" r = wintypes.RECT() user32.GetWindowRect(hwnd, ctypes.byref(r)) w, h = r.right - r.left, r.bottom - r.top if w <= 0 or h <= 0: return None, True hdc_win = user32.GetWindowDC(hwnd) hdc = gdi32.CreateCompatibleDC(hdc_win) bmp = gdi32.CreateCompatibleBitmap(hdc_win, w, h) old = gdi32.SelectObject(hdc, bmp) try: ok = user32.PrintWindow(wintypes.HWND(hwnd), hdc, PW_RENDERFULLCONTENT) if not ok: return None, True class BITMAPINFOHEADER(ctypes.Structure): _fields_ = [("biSize", wintypes.DWORD), ("biWidth", wintypes.LONG), ("biHeight", wintypes.LONG), ("biPlanes", wintypes.WORD), ("biBitCount", wintypes.WORD), ("biCompression", wintypes.DWORD), ("biSizeImage", wintypes.DWORD), ("biXPelsPerMeter", wintypes.LONG), ("biYPelsPerMeter", wintypes.LONG), ("biClrUsed", wintypes.DWORD), ("biClrImportant", wintypes.DWORD)] bi = BITMAPINFOHEADER(ctypes.sizeof(BITMAPINFOHEADER), w, -h, 1, 32, 0, 0, 0, 0, 0, 0) buf = ctypes.create_string_buffer(w * h * 4) gdi32.GetDIBits(hdc, bmp, 0, h, buf, ctypes.byref(bi), 0) raw = buf.raw # Sample every 97th byte for the black check (fast enough for 4K). black = max(raw[::97]) < 8 return hashlib.md5(raw).hexdigest(), black finally: gdi32.SelectObject(hdc, old) gdi32.DeleteObject(bmp) gdi32.DeleteDC(hdc) user32.ReleaseDC(hwnd, hdc_win) def set_tool_window(hwnd: int) -> None: """Hide from Alt+Tab / taskbar (tool window) and send to the bottom of the z-order.""" ex = user32.GetWindowLongPtrW(hwnd, GWL_EXSTYLE) user32.ShowWindow(hwnd, SW_HIDE) user32.SetWindowLongPtrW(hwnd, GWL_EXSTYLE, (ex | WS_EX_TOOLWINDOW) & ~WS_EX_APPWINDOW) user32.ShowWindow(hwnd, SW_SHOWNOACTIVATE) user32.SetWindowPos(hwnd, HWND_BOTTOM, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_FRAMECHANGED) def gpu_3d_by_pid() -> dict[int, float]: """3D engine utilisation per process from the 'GPU Engine' performance counters.""" script = ("$s=(Get-Counter '\\GPU Engine(*engtype_3D)\\Utilization Percentage' -ErrorAction SilentlyContinue)." "CounterSamples; $s | Select-Object InstanceName,CookedValue | ConvertTo-Json -Compress") try: out = subprocess.run(["powershell", "-NoProfile", "-NonInteractive", "-Command", script], capture_output=True, text=True, timeout=60).stdout.strip() rows = json.loads(out) if out else [] except Exception: return {} rows = rows if isinstance(rows, list) else [rows] usage: dict[int, float] = {} for row in rows: name = str(row.get("InstanceName", "")) if name.startswith("pid_"): try: pid = int(name.split("_")[1]) except ValueError: continue usage[pid] = round(usage.get(pid, 0.0) + float(row.get("CookedValue") or 0), 1) return usage def services_states(names: list[str]) -> dict[str, dict]: """Installed services and kernel drivers among ``names`` -> {name: {kind, state, start}}. Uses CIM so the answer does not depend on the Windows display language. """ quoted = ",".join("'" + n.replace("'", "") + "'" for n in names) script = (f"$n=@({quoted}); " "$a=@(Get-CimInstance Win32_Service | Where-Object { $n -contains $_.Name } | " "Select-Object Name,State,StartMode,@{n='Kind';e={'service'}}); " "$b=@(Get-CimInstance Win32_SystemDriver | Where-Object { $n -contains $_.Name } | " "Select-Object Name,State,StartMode,@{n='Kind';e={'driver'}}); " "ConvertTo-Json -Compress -InputObject @($a + $b)") try: out = subprocess.run(["powershell", "-NoProfile", "-NonInteractive", "-Command", script], capture_output=True, text=True, timeout=120).stdout.strip() rows = json.loads(out) if out else [] except Exception: return {} rows = rows if isinstance(rows, list) else [rows] return {r["Name"]: {"kind": r.get("Kind"), "state": r.get("State"), "start": r.get("StartMode")} for r in rows} def kill_tree(pid: int) -> None: subprocess.run(["taskkill", "/PID", str(pid), "/T", "/F"], capture_output=True) def kill_by_cmdline(fragment: str) -> None: """Stop processes whose command line contains ``fragment``. Chromium's first process can hand the window to another process and exit, so killing by the launched pid alone can leave the window open. """ frag = fragment.replace("'", "") script = (f"Get-CimInstance Win32_Process | Where-Object {{ $_.CommandLine -like '*{frag}*' }} | " "ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }") subprocess.run(["powershell", "-NoProfile", "-NonInteractive", "-Command", script], capture_output=True, timeout=60)