python中使用pyhook實現鍵盤監控的例子

來源:互聯網
上載者:User
pyhook下載:http://sourceforge.net/projects/pyhook/files/pyhook/1.5.1/

pyhookAPI手冊:http://pyhook.sourceforge.net/doc_1.5.0/

以上網站上提供了幾個使用的例子,另外安裝pyhooks後,也會有一個例子的檔案。於是拿來學習了一下,第一次運行時,提示沒有pythoncom模組,就安裝了pywin32,安裝後,可以正常運行,但是會導致機器發卡,特別是中斷程式運行後,滑鼠會出現一段時間的自由晃動,找了半天原因,感覺主要是事件頻率過高,程式會經常卡在pythoncom.PumpMessages()。

網上搜尋了半天,看到有一文章說是pythoncom.PumpMessages(n),n表示延遲時間,於是試著改了下,發現有一定效果,但不明顯,後來想是不是因為沒有終止程式,才會導致一直很卡呢,於是添加終止程式語句win32api.PostQuitMessage()。結果還算滿意。

# -*- coding: cp936 -*-import pythoncom import pyHook import timeimport win32apit=''asciistr=''keystr=''def onKeyboardEvent(event):    global t,asciistr,keystr  filename='d://test.txt'  wrfile=open(filename,'ab')  "處理鍵盤事件"  if t==str(event.WindowName):    asciistr=asciistr+chr(event.Ascii)    keystr=keystr+str(event.Key)      else:    t=str(event.WindowName)    if asciistr=='' and keystr=='':      wrfile.writelines("\nWindow:%s\n" % str(event.Window))      wrfile.writelines("WindowName:%s\n" % str(event.WindowName)) #寫入當前表單名      wrfile.writelines("MessageName:%s\n" % str(event.MessageName))      wrfile.writelines("Message:%d\n" % event.Message)      wrfile.writelines("Time:%s\n" % time.strftime('%Y-%m-%d %H:%M:%S',time.localtime()))    else:      wrfile.writelines("Ascii_char:%s\n" %asciistr)      wrfile.writelines("Key_char:%s\n" %keystr)      wrfile.writelines("\nWindow:%s\n" % str(event.Window))      wrfile.writelines("WindowName:%s\n" % str(event.WindowName)) #寫入當前表單名      wrfile.writelines("Time:%s\n" % time.strftime('%Y-%m-%d %H:%M:%S',time.localtime()))        asciistr=chr(event.Ascii)    keystr=str(event.Key)  if str(event.Key)=='F12': #按下F12後終止    wrfile.writelines("Ascii_char:%s\n" %asciistr)    wrfile.writelines("Key_char:%s\n" %keystr)    wrfile.close()      win32api.PostQuitMessage()      return True    if __name__ == "__main__":  #建立hook控制代碼   hm = pyHook.HookManager()   #監控鍵盤   hm.KeyDown = onKeyboardEvent   hm.HookKeyboard()   #迴圈擷取訊息   pythoncom.PumpMessages(10000)
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.