Python窗口激活

时间:2010-01-19 01:25:51

标签: python windows

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

4 个答案:

答案 0 :(得分:36)

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

答案 1 :(得分:5)

PywinautoSWAPY可能需要的工作量最少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 codethis会确保在运行上述代码之前显示它:

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

答案 2 :(得分:1)

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)

我们在这里。您只需要存储活动窗口的值即可。

答案 3 :(得分:0)

Pip 安装键盘。 在设置前景窗口之前,模拟一个键盘到 esc 即 keyboard.send('esc') 对于以下任一情况,您可能需要执行 3 次:

  1. 侧边栏
  2. Windows 键覆盖
  3. 始终在最前面的任务管理器
相关问题