Pyhook Download: HTTP://SOURCEFORGE.NET/PROJECTS/PYHOOK/FILES/PYHOOK/1.5.1/
PYHOOKAPI Manual: Http://pyhook.sourceforge.net/doc_1.5.0/
The above Web site provides several examples of use, in addition to installing pyhooks, there will also be an example of the file. So I took it to study, the first run, prompted no pythoncom module, installed the Pywin32, installed, can be normal operation, but will lead to machine hairpin, especially after the interruption of the program, the mouse will appear for a period of time free shaking, looking for a half-day reason, the main feeling is that the event frequency is too high , the program will often be stuck in the pythoncom. Pumpmessages ().
Online search for half a day, see a post that is pythoncom. Pumpmessages (n), n indicates the delay time, so try to change, found that there is a certain effect, but not obvious, later think is not because there is no termination of the program, will lead to a very card, then add the termination of the program statement Win32API. PostQuitMessage (). The result was satisfactory.
#-*-coding:cp936-*-import pythoncom import pyhook import time import win32api t= ' asciistr= ' keystr= ' def onkey Boardevent (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)) #写入当前窗体名 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 ("\nWindo w:%s\n "% str" (event. window)) wrfile.writelines ("windowname:%s\n"% str (event). WindOwname) #写入当前窗体名 wrfile.writelines ("time:%s\n"% time.strftime ('%y-%m-%d%h:%m:%s ', Time.localtime ())) ASci ISTR=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__": #创建hook句柄 HM = Pyhook.hookmanager () #监控键盘 Hm. KeyDown = Onkeyboardevent hm. Hookkeyboard () #循环获取消息 pythoncom. Pumpmessages (10000)