RetroEdge
RetroEdge

Reputation: 11

How do I detect if a window exists using python?

As the title says, I would like to know a way to detect if a window exists using python. I'm using this so I can close a window if a text file has 1 or more instances of a string. I know how to do the part to detect the string, and how to close the window (although if there is a better way to close a window without killing the process, other than ahk and pyautogui.press() than I would love to know) but I can't figure out how to detect if the window exists. For clarification, I want to detect the window, not the process, as the app being closed runs in the background as well.

Im rather bad at explaining things so if there is anything I need to explain please just ask.

One last thing, I'm using python 3.x

Upvotes: 1

Views: 3891

Answers (3)

Ashark
Ashark

Reputation: 843

If need this for linux, there is a wmctrl project, which could simplify that task.

Upvotes: 0

Federico
Federico

Reputation: 135

With this answer I enumerate all windows and check the window title:

import win32gui
def get_window_titles():
    ret = []
    def winEnumHandler(hwnd, ctx):
        if win32gui.IsWindowVisible(hwnd):
            txt = win32gui.GetWindowText(hwnd)
            if txt:
                ret.append((hwnd,txt))

    win32gui.EnumWindows(winEnumHandler, None)
    return ret

all_titles = get_window_titles()
window_starts = lambda title: [(hwnd,full_title) for (hwnd,full_title) in all_titles if full_title.startswith(title)]

all_matching_windows = window_starts('Untitled - Notepad')

Upvotes: 1

Schneyer
Schneyer

Reputation: 1257

Use the Python wrapper for AHK

from ahk import AHK

ahk = AHK()

win = ahk.win_get(title='Untitled - Notepad')
win.close()

Upvotes: 2

Related Questions