如何以編程方式激活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. 從彈出窗口激活父窗口
- 4. 如何激活窗口
- 5. 可可:激活窗口:shouldPopUpDocumentPathMenu:?
- 6. VBA激活Internet Explorer窗口
- 7. 激活控制檯窗口
- 8. wpf窗口未激活
- 9. 彈出窗口被激活
- 10. 重新激活以前激活的窗口/程序applescript?
- 11. 激活窗口/應用程序
- 12. autohotkey激活窗口兩次禁用它?
- 13. 激活隱藏進程的窗口
- 14. 如何激活現有的GVim窗口
- 15. 可可防止窗口激活
- 16. 如何激活給定窗口?
- 17. 如何在Java中激活窗口?
- 18. 沒有激活窗口樣式
- 19. 需要激活一個窗口
- 20. 使用VBA從Excel激活Word窗口
- 21. VSTO:MS Project - 激活項目窗口
- 22. 如何通知該窗口已激活?
- 23. 獲取上次激活窗口的窗口句柄
- 24. 爲什麼Django註冊使用「激活窗口」來激活帳戶?
- 25. 顯示窗口沒有激活(讓應用程序在它下面激活)
- 26. 激活的Python 2.7
- 27. 可能將激活的Microsoft Word窗口強制轉換爲WPF窗口?
- 28. 如何將窗口的Z-order設置爲剛好在激活的窗口下?
- 29. Windows窗體:激活方法和激活事件
- 30. 使用python查找活動窗口
你真的應該告訴我們您所使用的GUI工具包,因爲它是可能的,這種能力是在工具包。 – 2010-01-19 01:43:18
也許他正試圖激活任何一個打開的窗口? – 2010-01-19 03:53:49