2011-03-19 1840 views
3

我在想如何使用wxPython和win32apis一起創建一個簡單的腳本,它將激活一個帶有特定標題和輸出文本(擊鍵)的窗口(如果它尚未激活)。一個可能的應用程序將是遊戲中的鍵盤快捷鍵。我已經閱讀了wxPython RegisterHotKey(),但作爲業餘Python程序員,我不清楚。
腳本的基本結構是:Python中的簡單熱鍵腳本 - 如何設置全局熱鍵來發送一串文本?

  1. 定義熱鍵(類似WIN + F_)
  2. 手錶熱鍵按鍵
  3. 查看所需的窗口(標題)已經激活,並激活它,如果它不是
  4. 模擬一些文字

我知道有更簡單的方法來做到這一點(如AutoHotkey的)的類型,但我覺得更舒適能夠使用我自己寫的東西,並對Python感興趣。
謝謝!

爲了記錄,我在Windows 7 AMD64上使用Python 2.7,但我懷疑解釋器版本/平臺/體系結構在這裏有多大的區別。

+0

https://github.com/boppreh/keyboard – Andrew 2017-08-02 20:57:25

回答

4

您是否在討論激活您在wx中創建的窗口或單獨的應用程序(如記事本)?如果是wx,那麼它是微不足道的。您只需使用Raise()將您需要的任何框架帶入焦點。您可能會使用PubSub或PostEvent讓子框知道它需要提升。

如果你在談論記事本,那麼事情會變得更加粘性。下面是一個醜陋的黑客我創建基於一些東西,我從網上和PyWin32郵件列表上的不同位置有:

def windowEnumerationHandler(self, hwnd, resultList): 
    ''' 
    This is a handler to be passed to win32gui.EnumWindows() to generate 
    a list of (window handle, window text) tuples. 
    ''' 

    resultList.append((hwnd, win32gui.GetWindowText(hwnd))) 

def bringToFront(self, windowText): 
    ''' 
    Method to look for an open window that has a title that 
    matches the passed in text. If found, it will proceed to 
    attempt to make that window the Foreground Window. 
    ''' 
    secondsPassed = 0 
    while secondsPassed <= 5: 
     # sleep one second to give the window time to appear 
     wx.Sleep(1) 

     print 'bringing to front' 
     topWindows = [] 
     # pass in an empty list to be filled 
     # somehow this call returns the list with the same variable name 
     win32gui.EnumWindows(self.windowEnumerationHandler, topWindows) 
     print len(topWindows) 
     # loop through windows and find the one we want 
     for i in topWindows: 
      if windowText in i[1]: 
       print i[1] 
       win32gui.ShowWindow(i[0],5) 
       win32gui.SetForegroundWindow(i[0]) 
     # loop for 5-10 seconds, then break or raise 
     handle = win32gui.GetForegroundWindow() 
     if windowText in win32gui.GetWindowText(handle): 
      break 
     else: 
      # increment counter and loop again     
      secondsPassed += 1 

然後我用的SendKeys包文本發送到窗口(見http://www.rutherfurd.net/python/sendkeys/)。如果用戶打開其他任何東西,腳本將會中斷或發生奇怪的事情。如果您打開MS Office之類的東西,請使用win32com而不是SendKeys。這更可靠。

+0

謝謝!我將SendKeys視爲一種可能性,然而,最新版本是針對Python 2.6的,雖然它很可能向後兼容,但自安裝程序特別針對匹配的Python版本。 此外,通過「...腳本將打破或奇怪的事情將發生」,你的意思是如果用戶切換窗口,而鍵盤正在發送? – terrygarcia 2011-03-24 00:09:45

+0

是的,如果用戶在腳本運行時切換窗口,那麼SendKeys將繼續向任何焦點發送鍵,如果您不期待它,可能會造成混淆。 – 2011-03-24 18:22:04

+0

這並不是什麼大問題,但如果是這樣,是不是可以通過'while:'來解決?在那個代碼中,我可以替換窗口標題嗎?最後,SendKeys for Python 2.6是否可以與Python 2.7一起使用;我只是手動提取源到所需的模塊目錄?我** ** Windows作爲開發平臺;具有諷刺意味的是,我懶得重新安裝Ubuntu,它的啓動順序我被_installing_打破了Python包。 – terrygarcia 2011-03-24 22:59:12