您的位置:首页技术文章
文章详情页

Python如何设置指定窗口为前台活动窗口

【字号: 日期:2022-07-14 13:17:48浏览:5作者:猪猪

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

import re, timeimport webbrowserimport 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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持好吧啦网。

标签: Python 编程
相关文章: