pyhook下載:http://sourceforge.net/projects/pyhook/files/pyhook/1.5.1/
pyhookAPI手冊:http://pyhook.sourceforge.net/doc_1.5.0/
以上網(wǎng)站上提供了幾個使用的例子,另外安裝pyhooks后,也會有一個例子的文件。于是拿來學(xué)習(xí)了一下,第一次運行時,提示沒有pythoncom模塊,就安裝了pywin32,安裝后,可以正常運行,但是會導(dǎo)致機器發(fā)卡,特別是中斷程序運行后,鼠標(biāo)會出現(xiàn)一段時間的自由晃動,找了半天原因,感覺主要是事件頻率過高,程序會經(jīng)常卡在pythoncom.PumpMessages()。
網(wǎng)上搜索了半天,看到有一帖子說是pythoncom.PumpMessages(n),n表示延遲時間,于是試著改了下,發(fā)現(xiàn)有一定效果,但不明顯,后來想是不是因為沒有終止程序,才會導(dǎo)致一直很卡呢,于是添加終止程序語句win32api.PostQuitMessage()。結(jié)果還算滿意。
# -*- 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)) #寫入當(dāng)前窗體名 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)) #寫入當(dāng)前窗體名 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__": #創(chuàng)建hook句柄 hm = pyHook.HookManager() #監(jiān)控鍵盤 hm.KeyDown = onKeyboardEvent hm.HookKeyboard() #循環(huán)獲取消息 pythoncom.PumpMessages(10000)
新聞熱點
疑難解答
圖片精選