22

How do I get a list of the name/text of all opened windows?

I tried pywinauto:

pywinauto.findwindows.find_windows(title_re="*") but using * as a regex raises an error

I tried win32gui: It has

win32gui.GetWindowText(win32gui.GetForegroundWindow())

But in its docs I couldn't find a getAllWindows or something that returns all names/texts of open hwnd handles: http://timgolden.me.uk/pywin32-docs/contents.html

user10385242
  • 407
  • 1
  • 3
  • 10

3 Answers3

30

You can use win32gui.GetWindowText( hwnd ) along with win32gui.EnumWindows:

import win32gui

def winEnumHandler( hwnd, ctx ):
    if win32gui.IsWindowVisible( hwnd ):
        print ( hex( hwnd ), win32gui.GetWindowText( hwnd ) )

win32gui.EnumWindows( winEnumHandler, None )

Output:

0x20fa4 bet - [C:\Users\X\Desktop\] - [bet] - L:\stack\stack_enum_windows.py - IntelliJ IDEA 2017.2.5
0x1932478 13. vnc 888
0x30c27b8 Telegram (55)
0x40aba MobaXterm
0x10a0a IntelliJIDEALicenseServer_windows_amd64.exe - Shortcut
...
Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268
21

If you want using pywinauto, it's much easier:

from pywinauto import Desktop

windows = Desktop(backend="uia").windows()
print([w.window_text() for w in windows])

This should work even for WPF applications. Using win32gui.EnumWindows can't access texts for WPF or UWP applications. pywinauto uses win32gui.EnumWindows inside Desktop(backend="win32"). backend="uia" uses newer API from UIAutomationCore.dll.

More details about backends in pywinauto can be found in the Getting Started Guide.

Vasily Ryabov
  • 9,386
  • 6
  • 25
  • 78
10

You can also utilize pyautogui, by:

import pyautogui

for x in pyautogui.getAllWindows():  
    print(x.title)
Kostis Pagonis
  • 101
  • 1
  • 3
  • I find this much faster than pywinauto. You can also do `pyautogui.getAllTitles()` to get a list of all open window titles – Sludge Aug 10 '22 at 20:03
  • The `getAllWindows` and `getAllTitles` functions are no longer available. – Nav Sep 02 '22 at 14:17