I am trying to get a list of open windows. I am stuck at this point. I have commented everything that does not work so far.
import win32gui
def winEnumHandler(hwnd, ctx):
if win32gui.IsWindowVisible(hwnd):
if win32gui.GetWindowText(hwnd) != "":
wnd_name = win32gui.GetWindowText(hwnd)
print(f'Type: {type(wnd_name)} Name: {wnd_name}')
# return wnd_name
# return wnd_name
# return wnd_name
win32gui.EnumWindows(winEnumHandler, None)
This is an example of the output.
Type: <class 'str'> Name: vksts
Type: <class 'str'> Name: *new 10 - Notepad++
Type: <class 'str'> Name: _Chrome Downloads
Type: <class 'str'> Name: Microsoft Text Input Application
Type: <class 'str'> Name: Settings
Type: <class 'str'> Name: Program Manager
Although wnd_name is a string and I can print it, I can't figure out how to get its value to the main part of the script.
When I uncomment the 1st return wnd_name, I get the error message TypeError: an integer is required (got type str) for the line win32gui.EnumWindows(winEnumHandler, None).
When I uncomment the 2nd or 3rd return wnd_name, I get the error UnboundLocalError: local variable 'wnd_name' referenced before assignment for the line return wnd_name.
While win32gui.EnumWindows(winEnumHandler, None) is looping through the windows, how do I capture each window title and feed it to a list so that I end up with something like ['vksts','*new 10 - Notepad++','_Chrome Downloads',...]?