Python窗口激活

31 投票
8 回答
108656 浏览
提问于 2025-04-15 18:11

我想知道怎么用Python来程序化地激活Windows中的一个窗口。我现在的做法是先确保这个窗口是最后使用的应用程序,然后通过发送Alt+Tab的组合键来从命令行切换过去。不过我发现这种方法并不总是可靠,有没有更好的办法呢?

8 个回答

2
import ctypes, platform

if platform.system() == 'Windows':
    Active_W = ctypes.windll.user32.GetActiveWindow()
    ctypes.windll.user32.SetWindowPos(Active_W,0,0,0,0,0,0x0002|0x0001)

好了,你只需要保存当前活动窗口的值。

8

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()
60

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

撰写回答