Python窗口激活


问题内容

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


问题答案:

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