2016-04-29 193 views
0

所以我正在写一个记录击键的程序,它很好用,直到我点击离开程序框。当我点击柯塔娜像一个浏览器,并开始打字,它记录了几笔,然后完全停止。它也没有抛出任何错误,所以我不知道如何调试它。为什么pythoncom.pumpmessages()停止工作?

def run(self): 
    hm = pyHook.HookManager() 
    hm.KeyDown = self.OnKeyboardEvent 
    hm.HookKeyboard() 
    pythoncom.PumpMessages() 

def OnKeyboardEvent(self,event): 
     ch=chr(event.Ascii) 
     #print [ch] 
     if ch in '\x00\x08': 
      val='/*'+event.Key+'*/' 
      if (val!=self.prev or ch=='\x08') and 'Capital' not in val: 
       print val, 
       self.writetofile(str(val)) 
       data=shelve.open('loggerinfo') 
       data['strokes']=data['strokes'].append(val) 
       data.close() 
       self.prev=val 
     else: 
      self.prev=ch 
      char=None 
      if ch=='\r': 
       char='/*return*/' 
      elif ch=='\t': 
       char='/*tab*/' 
      else: 
       char=ch 
      if char!=None: 
       print char, 
       self.writetofile(str(char)) 
       data=shelve.open('loggerinfo') 
       data['strokes']=data['strokes'].append(char) 
       data.close() 
     return True 

我不知道是什么问题,因为它不会引发错误。

回答

1

问题是您的回调函数OnKeyBoardEvent需要在事件传播到系统其余部分之前返回True/False。这是因为pyHook是一个非常低级的拦截。

正如我最近发现,如果你的函数的时间太长返回True/False,pyHook将完全停止拦截按键。所以,你应该做的,就是建立一个线程,并立即返回True。这将让任何你想做异步执行。

类似下面。您可能需要查看锁以确保搁置不会被多个线程同时访问。

import threading  

def run(self): 
    hm = pyHook.HookManager() 
    hm.KeyDown = self.OnKeyboardEvent 
    hm.HookKeyboard() 
    pythoncom.PumpMessages() 

def ActOnEvent(event): 
    ch=chr(event.Ascii) 
    #print [ch] 
    if ch in '\x00\x08': 
     val='/*'+event.Key+'*/' 
     if (val!=self.prev or ch=='\x08') and 'Capital' not in val: 
      print val, 
      self.writetofile(str(val)) 
      data=shelve.open('loggerinfo') 
      data['strokes']=data['strokes'].append(val) 
      data.close() 
      self.prev=val 
    else: 
     self.prev=ch 
     char=None 
     if ch=='\r': 
      char='/*return*/' 
     elif ch=='\t': 
      char='/*tab*/' 
     else: 
      char=ch 
     if char!=None: 
      print char, 
      self.writetofile(str(char)) 
      data=shelve.open('loggerinfo') 
      data['strokes']=data['strokes'].append(char) 
      data.close()  

def OnKeyboardEvent(self,event): 
    threading.Thread(target=ActOnEvent, args=(event,)).start() 
    return True 
相关问题