window_picker.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. """List and select visible top-level Windows for capture."""
  2. from __future__ import annotations
  3. from dataclasses import dataclass
  4. from typing import List, Optional
  5. import win32con
  6. import win32gui
  7. @dataclass
  8. class WindowInfo:
  9. hwnd: int
  10. title: str
  11. rect: tuple # left, top, right, bottom
  12. def _is_candidate(hwnd: int) -> bool:
  13. if not win32gui.IsWindowVisible(hwnd):
  14. return False
  15. if win32gui.IsIconic(hwnd):
  16. return False
  17. title = win32gui.GetWindowText(hwnd)
  18. if not title or not title.strip():
  19. return False
  20. # Skip tool windows without a normal frame when possible.
  21. ex = win32gui.GetWindowLong(hwnd, win32con.GWL_EXSTYLE)
  22. if ex & win32con.WS_EX_TOOLWINDOW:
  23. return False
  24. left, top, right, bottom = win32gui.GetWindowRect(hwnd)
  25. if right - left < 80 or bottom - top < 80:
  26. return False
  27. return True
  28. def list_windows() -> List[WindowInfo]:
  29. found: List[WindowInfo] = []
  30. def _enum(hwnd, _):
  31. if _is_candidate(hwnd):
  32. title = win32gui.GetWindowText(hwnd)
  33. rect = win32gui.GetWindowRect(hwnd)
  34. found.append(WindowInfo(hwnd=hwnd, title=title, rect=rect))
  35. return True
  36. win32gui.EnumWindows(_enum, None)
  37. found.sort(key=lambda w: w.title.lower())
  38. return found
  39. def pick_window_interactive(title_substr: Optional[str] = None) -> WindowInfo:
  40. windows = list_windows()
  41. if title_substr:
  42. key = title_substr.lower()
  43. matched = [w for w in windows if key in w.title.lower()]
  44. if len(matched) == 1:
  45. return matched[0]
  46. if not matched:
  47. raise RuntimeError(f"No window matching title substr: {title_substr!r}")
  48. windows = matched
  49. if not windows:
  50. raise RuntimeError("No visible windows found.")
  51. print("Selectable windows:")
  52. for i, w in enumerate(windows):
  53. print(f" [{i}] hwnd={w.hwnd} {w.title}")
  54. while True:
  55. raw = input("Enter index to listen: ").strip()
  56. if not raw.isdigit():
  57. print("Please enter a number.")
  58. continue
  59. idx = int(raw)
  60. if 0 <= idx < len(windows):
  61. return windows[idx]
  62. print("Index out of range.")
  63. def get_client_screen_rect(hwnd: int) -> tuple:
  64. """Return (left, top, width, height) of client area in screen coords."""
  65. left, top, right, bottom = win32gui.GetClientRect(hwnd)
  66. # Client rect is relative; convert origin to screen.
  67. pt = win32gui.ClientToScreen(hwnd, (0, 0))
  68. width = right - left
  69. height = bottom - top
  70. return pt[0], pt[1], width, height