首页 > 代码库 > 利用Python的pyHook包来进行键盘监听

利用Python的pyHook包来进行键盘监听

最近在实习的时候发现一件很蛋疼的事情,那就是我们组的项目因为有后台进程,所有每次运行完以后后台进程都必须要自己手动关闭,每次编译之前忘记关就会有一大堆编译错误,我就想直接弄个可以快捷键直接关闭算了

 
做这个东西的首要原则就是要简单,那自然用python做是最好的了,我们可以用pyHook这个包就可以很方便做到监听键盘的功能
 
pyHook需要绑定一个消息处理函数,pyHook会传一个KeyboardEvent这样一个类进来
 
class KeyboardEvent(HookEvent):
    ‘‘‘
    Holds information about a mouse event.
    @ivar KeyID: Virtual key code
    @type KeyID: integer
    @ivar ScanCode: Scan code
    @type ScanCode: integer
    @ivar Ascii: ASCII value, if one exists
    @type Ascii: string
    ‘‘‘
    def __init__(self, msg, vk_code, scan_code, ascii, flags, time, hwnd, window_name):
        ‘‘‘Initializes an instances of the class.‘‘‘
        HookEvent.__init__(self, msg, time, hwnd, window_name)
        self.KeyID = vk_code
        self.ScanCode = scan_code
        self.Ascii = ascii
        self.flags = flags
    def GetKey(self):
        ‘‘‘
        @return: Name of the virtual keycode
        @rtype: string
        ‘‘‘
        return HookConstants.IDToName(self.KeyID)
    def IsExtended(self):
        ‘‘‘
        @return: Is this an extended key?
        @rtype: boolean
        ‘‘‘
        return self.flags & 0x01
    def IsInjected(self):
        ‘‘‘
        @return: Was this event generated programmatically?
        @rtype: boolean
        ‘‘‘
        return self.flags & 0x10
    def IsAlt(self):
        ‘‘‘
        @return: Was the alt key depressed?
        @rtype: boolean
        ‘‘‘
        return self.flags & 0x20
    def IsTransition(self):
        ‘‘‘
        @return: Is this a transition from up to down or vice versa?
        @rtype: boolean
        ‘‘‘
        return self.flags & 0x80
    Key = property(fget=GetKey)
    Extended = property(fget=IsExtended)
    Injected = property(fget=IsInjected)
    Alt = property(fget=IsAlt)
    Transition = property(fget=IsTransition)
 
虽然我觉得这个包有点不合理的地方就是没办法一下子拿到组合键,只能通过自己搞个规则来判断是不是组合键,不过能用就行
官网上已经有很完整的监听初始化例程了,我们可以把我们的消息处理封装到一个类中:
 
import pythoncom
import pyHook
import os
class KeyboardMgr:
    m_bZeroKeyPressed = False
    m_bShiftKeyPressed = False
    def on_key_pressed(self, event):
        if str(event.Key) == Lshift or str(event.Key) == Rshift and self.m_bZeroKeyPressed != True:
            self.m_bShiftKeyPressed = True
        if event.Alt == 32 and str(event.Key) == 0 and self.m_bShiftKeyPressed == True:
            os.system(TASKKILL /F /IM abc.exe /T)
        return True
    def on_key_up(self, event):
        if str(event.Key) == Lshift or str(event.Key) == Rshift:
            self.m_bShiftKeyPressed = False
        elif str(event.Key) == 0:
            self.m_bZeroKeyPressed = False
        return True
keyMgr = KeyboardMgr()
hookMgr = pyHook.HookManager()
hookMgr.KeyDown = keyMgr.on_key_pressed
hookMgr.KeyUp = keyMgr.on_key_up
hookMgr.HookKeyboard()
pythoncom.PumpMessages()
 
PS:注意pythoncom这个包的引用,可能会出现 No system module ‘pywintypes‘ 这样的错误,这个时候需要把lib\site-packages\win32路径下的pywintypes??.dll(问号是你的版本号)拷贝到lib\site-packages\win32\lib这里即可,如果遇到了类似的问题也是一样解决
 
杀死进程直接用windows的taskkill命令就可以了,这样每次调试前我只用按一下快捷键就可以后台进程全关了
 

利用Python的pyHook包来进行键盘监听