简体   繁体   中英

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:)

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://docs.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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM