如何以編程方式激活Windows中使用Python的窗口?我正在向它發送鍵擊,現在我只是確保它是最後一個應用程序,然後發送按鍵Alt + Tab從DOS控制檯切換到它。有沒有更好的方法(因爲我從經驗中學到這種方式絕不是萬無一失的)?Python窗口激活
回答
你可以使用win32gui模塊來做到這一點。首先,您需要獲得有效的窗口句柄。如果您知道窗口類名稱或確切標題,則可以使用win32gui.FindWindow
。如果沒有,您可以使用win32gui.EnumWindows
來枚舉窗口並嘗試找到合適的窗口。
一旦你有手柄,你可以用手柄撥打win32gui.SetForegroundWindow
。它會激活窗口,並準備好獲取您的擊鍵。
查看下面的示例。我希望它能幫助
import win32gui
import re
class WindowMgr:
"""Encapsulates some calls to the winapi for window management"""
def __init__ (self):
"""Constructor"""
self._handle = None
def find_window(self, class_name, window_name=None):
"""find a window by its class_name"""
self._handle = win32gui.FindWindow(class_name, window_name)
def _window_enum_callback(self, hwnd, wildcard):
"""Pass to win32gui.EnumWindows() to check all the opened windows"""
if re.match(wildcard, str(win32gui.GetWindowText(hwnd))) is not None:
self._handle = hwnd
def find_window_wildcard(self, wildcard):
"""find a window whose title matches the wildcard regex"""
self._handle = None
win32gui.EnumWindows(self._window_enum_callback, wildcard)
def set_foreground(self):
"""put the window in the foreground"""
win32gui.SetForegroundWindow(self._handle)
w = WindowMgr()
w.find_window_wildcard(".*Hello.*")
w.set_foreground()
當您同時打開同一個應用程序的多個實例時,這不起作用,因爲您無法區分它們(因爲它全部基於窗口標題)。這是一個真正的恥辱,但我想這是Win32API而不是這個特定的Python模塊? – dm76 2016-02-18 12:02:47
是否有類似的庫爲osx – 2017-02-14 03:15:07
hwnd代表什麼? (boo縮寫!) – NullVoxPopuli 2017-11-02 17:02:36
Pywinauto和SWAPY可能只需要最少的努力to set the focus of a window。
使用SWAPY如果發生意外,其他窗口都在關注的窗口,而不是一個問題前自動生成必要的檢索窗口對象的Python代碼,例如:
import pywinauto
# SWAPY will record the title and class of the window you want activated
app = pywinauto.application.Application()
t, c = u'WINDOW SWAPY RECORDS', u'CLASS SWAPY RECORDS'
handle = pywinauto.findwindows.find_windows(title=t, class_name=c)[0]
# SWAPY will also get the window
window = app.window_(handle=handle)
# this here is the only line of code you actually write (SWAPY recorded the rest)
window.SetFocus()
。 This additional code或this將確保它運行上面的代碼之前顯示:
# minimize then maximize to bring this window in front of all others
window.Minimize()
window.Maximize()
# now you can set its focus
window.SetFocus()
- 1. 激活窗口
- 2. popup沒有激活窗口被激活
- 3. Python:激活窗口在OS X
- 4. 窗口激活三個窗口同名
- 5. 從彈出窗口激活父窗口
- 6. wpf窗口未激活
- 7. 彈出窗口被激活
- 8. VBA激活Internet Explorer窗口
- 9. 可可:激活窗口:shouldPopUpDocumentPathMenu:?
- 10. 從gitbash激活pyvenv窗口
- 11. 如何激活窗口
- 12. 無法激活Excel窗口
- 13. 激活控制檯窗口
- 14. 重新激活以前激活的窗口/程序applescript?
- 15. 如何激活給定窗口?
- 16. 檢測標籤/窗口激活JavaScript中
- 17. 如何激活一個窗口?
- 18. 如何在Java中激活窗口?
- 19. SetForegroundWindow不會激活我的窗口
- 20. autohotkey激活窗口兩次禁用它?
- 21. 激活窗口/應用程序
- 22. 需要激活一個窗口
- 23. 窗口未激活時的Java輸入
- 24. 使用VBA從Excel激活Word窗口
- 25. 可可防止窗口激活
- 26. 如何使用Nircmd激活子窗口?
- 27. 沒有激活窗口樣式
- 28. 如何激活現有的GVim窗口
- 29. 激活隱藏進程的窗口
- 30. 如何通知該窗口已激活?
你真的應該告訴我們您所使用的GUI工具包,因爲它是可能的,這種能力是在工具包。 – 2010-01-19 01:43:18
也許他正試圖激活任何一個打開的窗口? – 2010-01-19 03:53:49