pyhook下載:http://sourceforge.net/projects/pyhook/files/pyhook/1.5.1/
pyhookAPI手冊:http://pyhook.sourceforge.net/doc_1.5.0/
以上網站上提供了幾個使用的例子,另外安裝pyhooks后,也會有一個例子的文件。于是拿來學習了一下,第一次運行時,提示沒有pythoncom模塊,就安裝了pywin32,安裝后,可以正常運行,但是會導致機器發卡,特別是中斷程序運行后,鼠標會出現一段時間的自由晃動,找了半天原因,感覺主要是事件頻率過高,程序會經??ㄔ趐ythoncom.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)
新聞熱點
疑難解答