初探hook的键盘获取
import pyHook import pythoncom class e(): keyIsPressed = False #键盘是否按下 按住。。 def onKeyDow(self,event): #键盘按下 if self.keyIsPressed: #如果键盘持续性按住,不再打印文字 return True print (str(event.Key) + ' is 按下') self.keyIsPressed = True #按下第一次 if (event.Key == 'E'): #如果按下e 则打印Efalse 并返回false 此次键盘按下的e被拦截不执行 print(str(event.Key) + ' FALSE') return False return True def onKeyU(self,event):#键盘抬起 self.keyIsPressed=False t_e=event.Key print(str(t_e) + ' is 抬起') if(t_e=='E'): #抬起的e不执行 # print(str(t_e) + ' FALSE') return False return True if __name__ == '__main__': mykbmanager = e() hookmanager = pyHook.HookManager() #创建一个钩子句柄 hookmanager.KeyDown = mykbmanager.onKeyDow hookmanager.KeyUp = mykbmanager.onKeyU hookmanager.HookKeyboard()#启动钩子 pythoncom.PumpMessages(10000)#用来维持住钩子,循环获取消息