pythonwin32gui

Bring window to focus with python periodically


import win32gui
import time

def windowEnumerationHandler(hwnd, top_windows):
    top_windows.append((hwnd, win32gui.GetWindowText(hwnd)))
if __name__ == "__main__":
    top_windows = []
    win32gui.EnumWindows(windowEnumerationHandler, top_windows)
    for i in top_windows:
        print(i)
        if "zoom" in i[1].lower():
            print(i, 'is found')
            while True:
                win32gui.ShowWindow(i[0],5)
                win32gui.SetForegroundWindow(i[0])
                time.sleep(1)

I've heard that zoom monitors whether the window is not in focus for more than 30 seconds, so I've been working on a way to repetitively throw it to the front while I work on other projects. The problem is the code raises an exception

0, 'SetForegroundWindow', 'No error message is available'

and the window just flashes yellow. Same problem with chrome as well. Would appreciate some help here :)


Solution

  • I had the same problem while I was trying to SetForegroundWindow(hwnd). The icon on the taskbar was just flashing, but the program stayed in the background. As you can read here: https://learn.microsoft.com/zh-cn/windows/win32/api/winuser/nf-winuser-setforegroundwindow?redirectedfrom=MSDN

    "An application cannot force a window to the foreground while the user is working with another window. Instead, Windows flashes the taskbar button of the window to notify the user."

    For me helped:

    import win32gui, win32com.client     
    
    
        shell = win32com.client.Dispatch("WScript.Shell")
        shell.SendKeys('%')
        win32gui.SetForegroundWindow(hwnd)