Python 窗口激活

新手上路,请多包涵

我将如何使用 Python 以编程方式激活 Windows 中的窗口?我正在向它发送击键,目前我只是确保它是最后一个使用的应用程序,然后发送击键 Alt+Tab 以从 DOS 控制台切换到它。有没有更好的方法(因为我从经验中了解到这种方法绝不是万无一失的)?

原文由 exupero 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1k
2 个回答

您可以使用 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()

原文由 luc 发布,翻译遵循 CC BY-SA 3.0 许可协议

PywinautoSWAPY 可能需要最少的努力 来设置窗口的焦点

使用 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()

如果碰巧其他窗口在感兴趣的窗口前面,这不是问题。 此附加代码 代码将确保在运行上述代码之前显示它:

 # minimize then maximize to bring this window in front of all others
window.Minimize()
window.Maximize()
# now you can set its focus
window.SetFocus()

原文由 ecoe 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题