1

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

RetroEdge
  • 11
  • 1
  • 3
  • 2
    Is this on windows, linux, mac? How would the window differ from the process? Does the process have multiple windows? Do you only want to close one window and not the entire process? – Brendan Abel Sep 25 '20 at 15:25

3 Answers3

2

Use the Python wrapper for AHK

from ahk import AHK

ahk = AHK()

win = ahk.win_get(title='Untitled - Notepad')
win.close()
Schneyer
  • 1,197
  • 1
  • 9
  • 27
1

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')
Federico
  • 138
  • 1
  • 12
0

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

Ashark
  • 643
  • 7
  • 16