Python程序运行时,打开了多个窗口,使用win32gui模块可以设置指定的某一个窗口为当前活动窗口。

import re, time
import webbrowser
import win32gui, win32con, win32com.client


def _window_enum_callback(hwnd, wildcard):
    '''
    Pass to win32gui.EnumWindows() to check all the opened windows
    把想要置顶的窗口放到最前面,并最大化
    '''
    if re.match(wildcard, str(win32gui.GetWindowText(hwnd))) is not None:
        win32gui.BringWindowToTop(hwnd)
        # 先发送一个alt事件,否则会报错导致后面的设置无效:pywintypes.error: (0, 'SetForegroundWindow', 'No error message is available')
        shell = win32com.client.Dispatch("WScript.Shell")
        shell.SendKeys('%')
        # 设置为当前活动窗口
        win32gui.SetForegroundWindow(hwnd)
        # 最大化窗口
        win32gui.ShowWindow(hwnd, win32con.SW_MAXIMIZE)


if __name__ == '__main__':
    webbrowser.open("https://www.baidu.com/")
    time.sleep(1)
    win32gui.EnumWindows(_window_enum_callback, ".*%s.*" % config.window_name)#此处为你要设置的活动窗口名

说明一点

有人会遇到这个错误(好吧,我也遇到了):

        pywintypes.error: (0, 'SetForegroundWindow', 'No error message is available')

Stack Overflow上的解决方法是添加如下代码:

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

即先发送一个alt key事件,这个错误就会避免,后面的设置才会有效。

链接地址:

https://stackoverflow.com/questions/14295337/win32gui-setactivewindow-error-the-specified-procedure-could-not-be-found

Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐