2010-01-19 196 views
9

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

+0

你真的应该告诉我们您所使用的GUI工具包,因为它是可能的,这种能力是在工具包。 – 2010-01-19 01:43:18

+1

也许他正试图激活任何一个打开的窗口? – 2010-01-19 03:53:49

回答

26

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

当您同时打开同一个应用程序的多个实例时,这不起作用,因为您无法区分它们(因为它全部基于窗口标题)。这是一个真正的耻辱,但我想这是Win32API而不是这个特定的Python模块? – dm76 2016-02-18 12:02:47

+0

是否有类似的库为osx – 2017-02-14 03:15:07

+1

hwnd代表什么? (boo缩写!) – NullVoxPopuli 2017-11-02 17:02:36

4

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