利用Python的pyHook包來進行鍵盤監聽

最近在實習的時候發現一件很蛋疼的事情,那就是咱們組的項目由於有後臺進程,全部每次運行完之後後臺進程都必需要本身手動關閉,每次編譯以前忘記關就會有一大堆編譯錯誤,我就想直接弄個能夠快捷鍵直接關閉算了python

 
作這個東西的首要原則就是要簡單,那天然用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命令就能夠了,這樣每次調試前我只用按一下快捷鍵就能夠後臺進程全關了
相關文章
相關標籤/搜索