Search code examples
pythonwin32gui

Python get specific window title


I want to be able to detect the presence of a specifically named window (in any process) to use as an "if" variable

After some research, I've concluded I must use the win32gui library (some posts also suggest ctypes), but most of the posts I find are about making a list of processes, and the only one that was related to this topic didn't answer the question properly. Perhaps I am too novice to understand it, but at last, I couldn't get it to work (the question was this one)

To exemplify what I want, I'll share a simple .vbs code that does that: It searches for a specific name (in our case, steve jobs) and if it finds it anywhere, it triggers (in this example, it closes said process)

do
WindowTitle = "steve jobs"
set shell = createObject("wscript.shell") 
success = shell.appactivate(WindowTitle)
if success then shell.sendkeys "%{F4}" 
loop

Solution

  • import win32gui
    
    win2find = input('enter name of window to find')
    whnd = win32gui.FindWindowEx(None, None, None, win2find)
    if not (whnd == 0):
      print('FOUND!')
    

    You can search Google for 'FindWindowEx'

    to find https://msdn.microsoft.com/en-us/library/windows/desktop/ms633500(v=vs.85).aspx

    for a description of the FindWindowEx function