How to use win32gui FindWindow with Wildcard

77120 picture 77120 · Jan 24, 2014 · Viewed 15.9k times · Source

I am trying to find if Microsoft excel has an open window

import win32ui
import time

def WindowExists(windowname):
    try:
        win32ui.FindWindow(None, windowname)

    except win32ui.error:
        return False
    else:
        return True

if WindowExists("filename - Microsoft Excel"):
    print "Program is running"
    time.sleep(10)
else:
    print "Program is not running"
    time.sleep(10)

this works if i enter the correct filename, but the thing is i dont know the filename. so how can i get this work when only knowing part of the title?

or must i search on the classname instead? if so how do i know the classname :)?

extra note: i do know the filename but it has a unknow number attached to it, something like filename88, and differs every time i run the program.

Answer

rabs picture rabs · Jan 24, 2014
def find_filename(substring):
    import os
    import re
    files = os.listdir(os.getcwd())
    for file in files:
        search = re.search(substring, file)
        if search:
            filename = file
            break
    return filename

file = find_filename('stringyouwant')
WindowExists(file)

This function will return the full filename that contains the shorter string that you require - however it will only work if the file you are searching for is the only file with that substring in that directory. If you want something more robust, you should modify the regular expression.