"""List and select visible top-level Windows for capture.""" from __future__ import annotations from dataclasses import dataclass from typing import List, Optional import win32con import win32gui @dataclass class WindowInfo: hwnd: int title: str rect: tuple # left, top, right, bottom def _is_candidate(hwnd: int) -> bool: if not win32gui.IsWindowVisible(hwnd): return False if win32gui.IsIconic(hwnd): return False title = win32gui.GetWindowText(hwnd) if not title or not title.strip(): return False # Skip tool windows without a normal frame when possible. ex = win32gui.GetWindowLong(hwnd, win32con.GWL_EXSTYLE) if ex & win32con.WS_EX_TOOLWINDOW: return False left, top, right, bottom = win32gui.GetWindowRect(hwnd) if right - left < 80 or bottom - top < 80: return False return True def list_windows() -> List[WindowInfo]: found: List[WindowInfo] = [] def _enum(hwnd, _): if _is_candidate(hwnd): title = win32gui.GetWindowText(hwnd) rect = win32gui.GetWindowRect(hwnd) found.append(WindowInfo(hwnd=hwnd, title=title, rect=rect)) return True win32gui.EnumWindows(_enum, None) found.sort(key=lambda w: w.title.lower()) return found def pick_window_interactive(title_substr: Optional[str] = None) -> WindowInfo: windows = list_windows() if title_substr: key = title_substr.lower() matched = [w for w in windows if key in w.title.lower()] if len(matched) == 1: return matched[0] if not matched: raise RuntimeError(f"No window matching title substr: {title_substr!r}") windows = matched if not windows: raise RuntimeError("No visible windows found.") print("Selectable windows:") for i, w in enumerate(windows): print(f" [{i}] hwnd={w.hwnd} {w.title}") while True: raw = input("Enter index to listen: ").strip() if not raw.isdigit(): print("Please enter a number.") continue idx = int(raw) if 0 <= idx < len(windows): return windows[idx] print("Index out of range.") def get_client_screen_rect(hwnd: int) -> tuple: """Return (left, top, width, height) of client area in screen coords.""" left, top, right, bottom = win32gui.GetClientRect(hwnd) # Client rect is relative; convert origin to screen. pt = win32gui.ClientToScreen(hwnd, (0, 0)) width = right - left height = bottom - top return pt[0], pt[1], width, height