def test_parse_hotkey_example(self): alt_codes = keyboard.key_to_scan_codes('alt') shift_codes = keyboard.key_to_scan_codes('shift') a_codes = keyboard.key_to_scan_codes('a') b_codes = keyboard.key_to_scan_codes('b') c_codes = keyboard.key_to_scan_codes('c') self.assertEqual(keyboard.parse_hotkey("alt+shift+a, alt+b, c"), ((alt_codes, shift_codes, a_codes), (alt_codes, b_codes), (c_codes,)))
def test_parse_hotkey_example(self): alt_codes = keyboard.key_to_scan_codes('alt') shift_codes = keyboard.key_to_scan_codes('shift') a_codes = keyboard.key_to_scan_codes('a') b_codes = keyboard.key_to_scan_codes('b') c_codes = keyboard.key_to_scan_codes('c') self.assertEqual(keyboard.parse_hotkey("alt+shift+a, alt+b, c"), ((alt_codes, shift_codes, a_codes), (alt_codes, b_codes), (c_codes, )))
def set_key_map(target, replacement): if len(keyboard.key_to_scan_codes( target, error_if_missing=False)) > 0 and len( keyboard.key_to_scan_codes(replacement, error_if_missing=False)) > 0: logger.info("mapping %s to %s" % (target, replacement)) f = lambda event: keyboard.send( replacement) if event.event_type == keyboard.KEY_DOWN else None return keyboard.hook_key(target, f, suppress=True) else: logger.warning("Could not map '%s' to '%s', bad config" % (target, replacement))
def parse_config(config_file): config = configparser.ConfigParser() config.read(config_file) key_fallback = [] modkeys = [] hotkeys = [] for layer in config.sections(): # key fallback key_fallback.append(config[layer]['key_fallback']) # modkeys config_modkeys = config[layer]['modkeys'].strip().split('\n') layer_modkeys = {} for key in config_modkeys: key = key.split('=') key_code = int(key[0]) key_action = key[1][1:].split(',') key_action[1] = int(key_action[1]) layer_modkeys[key_code] = tuple(key_action) modkeys.append(layer_modkeys) # hotkeys config_hotkeys = config[layer]['hotkeys'].strip().split('\n') layer_hotkeys = {} for key in config_hotkeys: key = key.split('=') map_key = key[0].split(',') map_key = [key.strip(' ') for key in map_key] map_key_list = [] remap_key = key[1].split(',') remap_key = [key.strip(' ') for key in remap_key] remap_key_list = [] for key in map_key: key = keyboard.key_to_scan_codes(key)[0] map_key_list.append(key) map_key = tuple(map_key_list) for key in remap_key: key = keyboard.key_to_scan_codes(key)[0] remap_key_list.append(key) remap_key = tuple(remap_key_list) remap_key = keyboard.key_to_scan_codes(remap_key) layer_hotkeys[map_key] = remap_key hotkeys.append(layer_hotkeys) return key_fallback, modkeys, hotkeys
def getKeyForBtn(btn): key = keyboard.read_key() if key != "esc": btn['text'] = key logger.debug( "(settings_menu) detected key '{}' with scancode {}".format( key, keyboard.key_to_scan_codes(key)))
def recievingKeyboardThreadFunc(conn): data = loads(recv_msg(conn).decode()) while data: print data for evt in data["events"]["keyboard"]: print evt try: scan_code = keyboard.key_to_scan_codes(chr(evt["code"]))[0] except ValueError: try: scan_code = keycodes[evt["code"]] except IndexError: continue if evt["type"] == "DOWN": keyboard.press(scan_code) else: keyboard.release(scan_code) for evt in data["events"]["mouse"]: print "MOUSEEVENT:", evt if evt == "Move": newPos = evt["pos"] mouse.move(newPos[0], newPos[1], duration=0.15) elif evt == "LeftDown": mouse.press() elif evt == "LeftUp": mouse.release() try: recieved = recv_msg(conn).decode() except socket.error: break data = loads(recieved)
def sp(name): try: return keyboard.key_to_scan_codes(str(name))[0] except: try: return media_keys[str(name)] except: return None
def sp(name): try: return keyboard.key_to_scan_codes(str(name))[0] except ValueError: try: return media_keys[str(name)] except KeyError: return None
def keyboard_press(self, value: str): """ Generates a keypress press """ try: if "+" in value and len(value) > 1: keyboard.parse_hotkey(value) else: keyboard.key_to_scan_codes(value) except ValueError as e: if str(e).startswith("Unexpected key type"): return "notReadable" else: return "notMapped" if self.debug: self._list.append(f"print('Pressing {str(value)}')") self._list.append(f"keyboard.press_and_release('{value}')") return True
def cb_key(keyL, keyU, keyCL, keyCU, dir=None): sckeyL = min(keyboard.key_to_scan_codes(keyL)) sckeyU = min(keyboard.key_to_scan_codes(keyU)) sckeyCL = min(keyboard.key_to_scan_codes(keyCL)) sckeyCU = min(keyboard.key_to_scan_codes(keyCU)) def cb_key_fn(e): if keyboard.is_pressed('capslock'): if keyboard.is_pressed('shift'): keyboard.press_and_release(sckeyCU) elif keyboard.is_pressed('tab') and dir is not None: keyboard.press_and_release(dir) else: keyboard.press_and_release(sckeyCL) else: if keyboard.is_pressed('shift'): keyboard.press_and_release(sckeyU) else: keyboard.press_and_release(sckeyL) return cb_key_fn
def __getInput(self): up = key_to_scan_codes('up')[0] down = key_to_scan_codes('down')[0] left = key_to_scan_codes('left')[0] right = key_to_scan_codes('right')[0] esc = key_to_scan_codes('esc')[0] while not self.__exit: if keyboardInput.isActive( up) and self.__snake.getDirection() != Direction.DOWN: self.__snake.setDirection(Direction.UP) elif keyboardInput.isActive( down) and self.__snake.getDirection() != Direction.UP: self.__snake.setDirection(Direction.DOWN) elif keyboardInput.isActive( left) and self.__snake.getDirection() != Direction.RIGHT: self.__snake.setDirection(Direction.LEFT) elif keyboardInput.isActive( right) and self.__snake.getDirection() != Direction.LEFT: self.__snake.setDirection(Direction.RIGHT) elif keyboardInput.isClicked(esc): self.__exit = True sleep(0.0001)
def keyToConBtn(key): #this method translates recorded key events to respective controller buttons pressed for recording playback namedKey = None keyBinding = {'q': 'left', 'w': 'lStickUp', 'e': 'up', 'r': 'zl', 't': 'l', 'y': 'r', 'u': 'zr', 'i': 'rStickUp', 'a': 'lStickL', 's': 'lStickDown', 'd': 'lStickR', 'f': 'right', 'g': 'capture', 'h': 'home', 'j': 'rStickL', 'k': 'rStickDown', 'l': 'rStickR', 'c': 'down', 'up': 'x', 'down': 'b', 'left': 'y', 'right': 'a', '[': 'minus', ']': 'plus'} testKeys = ['q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'c', 'up', 'down', 'left', 'right', '+', '-'] for testKey in testKeys: testKeyCode = keyboard.key_to_scan_codes(testKey) #print('testKeyCode:') #print(testKeyCode) if testKeyCode[0] == key: namedKey = testKey #print('namedKey:') #print(namedKey) if namedKey in keyBinding: conBtnPressed = keyBinding[namedKey] return conBtnPressed
def getch_new(): """ Processing keystrokes by scancode. Provides work independent of the national layout. """ scan_key = { 2: 49, 3: 50, 4: 51, 5: 52, 6: 53, 7: 54, 8: 55, 9: 56, 10: 57, 11: 48, 35: 72, 19: 82, 44: 90, 32: 68, 31: 83, 21: 89, 16: 81, 50: 77, 46: 67, 33: 70, 18: 69, 22: 85, 38: 76, 23: 73, 24: 79 } if 1: s1 = keyboard.read_key(False) s1 = keyboard.read_key(False) a = keyboard.key_to_scan_codes(s1)[0] try: s = chr(scan_key[a]) except: if len(s1) == 1: s1 = "" s = " " print("Invalid key {}".format(s1)) keyboard.send(key_esc, do_press=True, do_release=True) return s
def __key_on(self, e): if (e.name == 'r' and e.event_type == 'up' and keyboard.key_to_scan_codes("alt")[0] in keyboard._pressed_events and keyboard.key_to_scan_codes("ctrl")[0] in keyboard._pressed_events): if self.mode == 'Pause': self.started_recording_with_keyboard = True self.start_recording() elif self.mode == 'Record': self.stop_recording() elif self.mode == 'Stop': self.main_overlay.refresh() self.mode = 'Pause' elif ((e.name == 'q') and (e.event_type == 'up') and keyboard.key_to_scan_codes("alt")[0] in keyboard._pressed_events and keyboard.key_to_scan_codes("ctrl")[0] in keyboard._pressed_events): self.mode = 'Quit' self.quit() elif ((e.name == 'F') and (e.event_type == 'up') and keyboard.key_to_scan_codes("shift")[0] in keyboard._pressed_events and keyboard.key_to_scan_codes("ctrl")[0] in keyboard._pressed_events): if self.last_element_event: x, y = win32api.GetCursorPos() l_e_e = self.last_element_event rx, ry = l_e_e.rectangle.mid_point() dx, dy = float(x - rx) / (l_e_e.rectangle.width() - 1), float( y - ry) / (l_e_e.rectangle.height() - 1) str_dx, str_dy = "{:.2f}".format(round(dx * 100, 2)), "{:.2f}".format( round(dy * 100, 2)) self.main_overlay.add(geometry=oaam.Shape.image, hicon=self.hicon, x=x, y=l_e_e.rectangle.top - 70) i = l_e_e.path.find(path_separator) window_title = l_e_e.path[0:i] #element_path = l_e_e.path[i+len(path_separator):] p = get_relative_path(window_title, l_e_e.path) pyperclip.copy('with Window(u"' + escape_special_char(window_title) + '"):\n' + '\twrapper = find(u"' + escape_special_char(p) + '%(' + str_dx + ',' + str_dy + ')")\n') if self.event_list: self.event_list.append( FindEvent(path=l_e_e.path, dx=dx, dy=dy, time=time.time())) elif self.mode == 'Record': self.event_list.append(e)
def set_hotkey(self, hotkey): self.listener.stop() sender = self.sender() dialog = AddHotkeyDialog(self) dialog.show() QApplication.processEvents() input = keyboard.read_hotkey(suppress=False) dialog.close() if input != 'esc': if hotkey_delete_request(input): self.settings.hotkeys[hotkey] = '' self.buttons[hotkey].setText('') elif hotkey_is_numlock(input): scan_code = keyboard.key_to_scan_codes(input)[1] reply = QMessageBox.question( self, 'Save Hotkey?', f'New Hotkey: Num{input}.\n Save Hotkey?') if reply == QMessageBox.Yes: for k, hk in self.settings.hotkeys.items(): if hk == scan_code: self.settings.hotkeys[k] = '' self.buttons[k].setText('') self.settings.hotkeys[hotkey] = scan_code sender.setText(f'Num{input}') else: reply = QMessageBox.question( self, 'Save Hotkey?', f'New Hotkey: {input}.\n Save Hotkey?') if reply == QMessageBox.Yes: for k, hk in self.settings.hotkeys.items(): if hk == input: self.settings.hotkeys[k] = '' self.buttons[k].setText('') self.settings.hotkeys[hotkey] = input sender.setText(input) if not self.listener.paused: self.listener.start() # TODO: Wenn man seinen Pause key deleted elif self.settings.hotkeys['pause']: keyboard.add_hotkey(self.settings.hotkeys['pause'], self.listener.pause)
def unhook_hotkey(self): if self.hotkey_hook is not None: Macro.key_macro_count[self.key] -= 1 # Fragile: Based on remove_ function from hook_key # Remove own listener del keyboard._hooks[self.__action] # Remove the hotkey remover del keyboard._hooks[self.hotkey_hook] # Only remove the global key hook if nobody else is listening. # This is the code that keyboard didn't support. if Macro.key_macro_count[self.key] == 0: del keyboard._hooks[self.key] # Remove self from scancode listener scan_codes = keyboard.key_to_scan_codes(self.key) # Important: If we ever supress keys, we need to use # _listener.blocking_keys instead. store = keyboard._listener.nonblocking_keys for scan_code in scan_codes: if self.__action in store[scan_code]: store[scan_code].remove(self.__action) self.hotkey_hook = None
def player_control(self): #if keyboard.is_pressed('q'): # if key 'q' is pressed #self.finished = True if self.player == 1: if keyboard.is_pressed(keyboard.key_to_scan_codes("left arrow")): self.movePlayer(-config.speed, 0) if keyboard.is_pressed(keyboard.key_to_scan_codes("right arrow")): self.movePlayer(config.speed, 0) if keyboard.is_pressed(keyboard.key_to_scan_codes("up arrow")): self.movePlayer(0, -config.speed) if keyboard.is_pressed(keyboard.key_to_scan_codes("down arrow")): self.movePlayer(0, config.speed) elif self.player == 2: if keyboard.is_pressed(keyboard.key_to_scan_codes("a")): self.movePlayer(-config.speed, 0) if keyboard.is_pressed("d"): self.movePlayer(config.speed, 0) if keyboard.is_pressed(keyboard.key_to_scan_codes("w")): self.movePlayer(0, -config.speed) if keyboard.is_pressed(keyboard.key_to_scan_codes("s")): self.movePlayer(0, config.speed)
def test_key_to_scan_code_from_normalized(self): self.assertEqual(keyboard.key_to_scan_codes('shift'), (5, 6)) self.assertEqual(keyboard.key_to_scan_codes('SHIFT'), (5, 6)) self.assertEqual(keyboard.key_to_scan_codes('ctrl'), keyboard.key_to_scan_codes('CONTROL'))
def test_key_to_scan_code_from_letter(self): self.assertEqual(keyboard.key_to_scan_codes('a'), (1, )) self.assertEqual(keyboard.key_to_scan_codes('A'), (1, -1))
def test_key_to_scan_code_from_scan_code(self): for i in range(10): self.assertEqual(keyboard.key_to_scan_codes(i), (i, ))
def test_key_to_scan_code_error_none(self): with self.assertRaises(ValueError): keyboard.key_to_scan_codes(None)
def test_key_to_scan_code_duplicated(self): self.assertEqual(keyboard.key_to_scan_codes('duplicated'), (20, ))
def test_key_to_scan_code_list(self): self.assertEqual(keyboard.key_to_scan_codes([10, 5, 'a']), (10, 5, 1))
def test_key_to_scan_code_from_scan_code(self): for i in range(10): self.assertEqual(keyboard.key_to_scan_codes(i), (i,))
def test_key_to_scan_code_from_letter(self): self.assertEqual(keyboard.key_to_scan_codes('a'), (1,)) self.assertEqual(keyboard.key_to_scan_codes('A'), (1,-1))
def test_key_to_scan_code_from_normalized(self): self.assertEqual(keyboard.key_to_scan_codes('shift'), (5,6)) self.assertEqual(keyboard.key_to_scan_codes('SHIFT'), (5,6)) self.assertEqual(keyboard.key_to_scan_codes('ctrl'), keyboard.key_to_scan_codes('CONTROL'))
def test_key_to_scan_code_from_sided_modifier(self): self.assertEqual(keyboard.key_to_scan_codes('left shift'), (5,)) self.assertEqual(keyboard.key_to_scan_codes('right shift'), (6,))
def test_key_to_scan_code_underscores(self): self.assertEqual(keyboard.key_to_scan_codes('_'), (12,)) self.assertEqual(keyboard.key_to_scan_codes('right_shift'), (6,))
def test_key_to_scan_code_from_sided_modifier(self): self.assertEqual(keyboard.key_to_scan_codes('left shift'), (5, )) self.assertEqual(keyboard.key_to_scan_codes('right shift'), (6, ))
def test_key_to_scan_codes_brute(self): for name, entries in dummy_keys.items(): if name in ['none', 'duplicated']: continue expected = tuple(scan_code for scan_code, modifiers in entries) self.assertEqual(keyboard.key_to_scan_codes(name), expected)
def test_key_to_scan_code_underscores(self): self.assertEqual(keyboard.key_to_scan_codes('_'), (12, )) self.assertEqual(keyboard.key_to_scan_codes('right_shift'), (6, ))
def get(self, key): # 一个字符一般对应两个扫描码 return keyboard.key_to_scan_codes(key)
def test_key_to_scan_code_error_other(self): with self.assertRaises(ValueError): keyboard.key_to_scan_codes({})
def test_key_to_scan_code_duplicated(self): self.assertEqual(keyboard.key_to_scan_codes('duplicated'), (20,))
def test_key_to_scan_code_empty(self): with self.assertRaises(ValueError): keyboard.key_to_scan_codes('none')
def isActiveByName(name: str) -> bool: return keyboardInput.isActive(keyboard.key_to_scan_codes(name)[0])
def ret_one_scancode(self, key): # 只返回一个 return keyboard.key_to_scan_codes(key)[0]