定期将 window 与 python 一起聚焦

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)

我听说zoom会监控window是否超过30秒没有对焦,所以我一直在研究一种方法,在我处理其他的时候,把它重复地扔到前面项目。问题是代码引发异常

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

并且 window 只是闪烁黄色。 chrome 也有同样的问题。在此感谢您的帮助:)

我在尝试 SetForegroundWindow(hwnd) 时遇到了同样的问题。任务栏上的图标只是闪烁,但程序留在后台。你可以在这里阅读: 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."

对我有帮助:

import win32gui, win32com.client     


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