Python 窗口激活 [英] Python Window Activation

查看:115
本文介绍了Python 窗口激活的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How would I programmatically activate a window in Windows using Python? I'm sending keystrokes to it and at the moment I'm just making sure it's the last application used then sending the keystroke Alt+Tab to switch over to it from the DOS console. Is there a better way (since I've learned by experience that this way is by no means foolproof)?

推荐答案

您可以使用 win32gui 模块来做到这一点.首先,您需要在窗口上获得有效句柄.如果您知道窗口类名称或确切标题,则可以使用 win32gui.FindWindow.如果没有,您可以使用 win32gui.EnumWindows 枚举窗口并尝试找到正确的窗口.

You can use the win32gui module to do that. First you need to get a valid handle on your window. You can use the win32gui.FindWindow if you know the window class name or the exact title. If not, you can enumerate the windows with the win32gui.EnumWindows and try to find the right one.

获得句柄后,您可以使用句柄调用win32gui.SetForegroundWindow.它将激活窗口并准备好接收您的按键.

Once you have the handle, you can call the win32gui.SetForegroundWindow with the handle. It will activate the window and will be ready for getting your keystrokes.

请参阅下面的示例.希望能帮到你

See an example below. I hope it helps

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

这篇关于Python 窗口激活的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆