如何以编程方式激活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