在使用python的過程中,有時會遇到這種需求:開啟了很多窗口,需要把焦點鎖定到某個進程的窗口上,再對該窗口進行操作。例如:我們打開了notepad.exe和wordpad.exe應用程序,現在需要把焦點定位到notepad窗口上,在notepad窗口中進行輸入。
參考代碼如下,其原理為:通過獲取進程的pid來遍歷該進程下的所有窗口,由于notepad.exe只有一個窗口,所以可得到一個窗口的句柄。再調用win32gui的SetForegroundWindow(hwnd),把該hwnd置首。
import win32con
import win32gui
import win32process
def get_hwnds_for_pid (pid):
? ? def callback (hwnd, hwnds):
? ? ? ? if win32gui.IsWindowVisible (hwnd) and win32gui.IsWindowEnabled (hwnd):
? ? ? ? ? ? _, found_pid = win32process.GetWindowThreadProcessId (hwnd)
? ? ? ? ? ? if found_pid == pid:
? ? ? ? ? ? ? ? hwnds.append (hwnd)
? ? ? ? ? ? return True
? ? hwnds = []
? ? win32gui.EnumWindows (callback, hwnds)
? ? return hwnds
if __name__ == '__main__':
? ? import subprocess
? ? import time
? ? notepad = subprocess.Popen ([" ?notepad.exe"])
? ? #
? ? # sleep to give the window time to appear
? ? #
? ? time.sleep (2.0)
? ? print (notepad.pid)
? ? for hwnd in get_hwnds_for_pid (notepad.pid):
? ? ? ? print (hwnd, "=>", win32gui.GetWindowText (hwnd))
? ? ? ? win32gui.SetForegroundWindow(hwnd)
我們使用pywinauto庫,其中的HwndWrapper類中有SetFocus函數,該函數在實踐過程中有些情況下會失效。可修改SetFocus函數,在其開始處先嘗試執行如下代碼:
1ctypes.windll.user32.SwitchToThisWindow(self.handle,True)2win32functions.SetFocus(self)
如果發生異常,再繼續執行原來的內容。