您的位置:首页 > 编程语言 > Python开发

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

2020-08-16 04:09 1181 查看

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

以上就是本文的全部内容,希望对大家的学习有所帮助

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Python 设置 前台 窗口