Python窗口激活

我将如何以编程方式激活Windows中使用Python的窗口? 我正在向它发送键击,现在我只是确保它是最后一个应用程序,然后发送按键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))) != None: self._handle = hwnd def find_window_wildcard(self, wildcard): 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() 

Pywinauto和SWAPY可能需要最少的努力设置窗口的焦点 。

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