Pyhooks
Download:Http://sourceforge.net/projects/pyhook/files/pyhook/1.5.1/
API manual:Http://pyhook.sourceforge.net/doc_1.5.0/
An example is provided on the above website. In addition, after installing pyhooks, there will also be an example file. So I learned how to install pywin32 when I first run it, prompting that the pythoncom module is not available. After the installation, it can run normally, but it will cause the machine to issue a card, especially the interruption.ProgramAfter running, the mouse will shake freely for a period of time. After looking for reasons for half a day, I feel that the event frequency is too high, and the program will often be stuck in pythoncom. pumpmessages ().
I searched the internet for half a day and saw a Post saying it was pythoncom. pumpmessages (N), N indicates the delay time, so I tried to change it and found it had some effect, but it was not obvious. Then I wondered if the program was not terminated because, the program is always stuck, so the program termination statement WIN32API is added. postquitmessage (). The results are 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 ' )
" Handle 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: % s \ n " % STR (event. Window ))
Wrfile. writelines ( " Windowname: % s \ n " % STR (event. windowname )) # Write the name of the current form
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 )) # Write the name of the current form
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 ' : # Terminate after F12 is pressed
Wrfile. writelines ( " Ascii_char: % s \ n " % Asciistr)
Wrfile. writelines ( " Key_char: % s \ n " % Keystr)
Wrfile. Close ()
WIN32API. postquitmessage ()
Return True
If _ Name __ = " _ Main __ " :
'''
Small Five: http://www.cnblogs.com/xiaowuyi
'''
# Create hook handle
Hm = pyhook. hookmanager ()
# Monitoring keyboard
Hm. keydown = onkeyboardevent
Hm. hookkeyboard ()
# Obtain messages cyclically
Pythoncom. pumpmessages (10000)