Python如何設置指定窗口為前臺活動窗口
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
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章: