2010-01-19 653 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()