def startHooks(): """ Attaches keyboard hooks, starts the program basically. """ # Avoid duplicate hooks by removing all hooks first #stopHooks() # Hook all keys # Issues: fails with 'left windows', types a 'd' when shift is pressed, etc. #kb.hook(hookCallback, True) # supress characters # Hook only letters (and maybe certain other characters) for character in config['hookKeys']: kb.hook_key(character, hookCallback, True) # supress characters for character in config['listenKeys']: kb.hook_key(character, listenCallback, False) # don't supress characters if config['printDebug']: printf("\nAttached {} hooks.".format(len(config['hookKeys']))) # wait forever (only useful for when this function is the last thing called, not for system tray) if not config["enableSysTray"]: kb.wait()
def __enter__(self): kb.hook_key( self.key_name, self.callbackWrapper, suppress=True, ) kb.press(self.key_name)
def main(): noise.intialize_noise(conf['selected_noise'], conf['volume_offset']) create_tables() read_config() # keyboard.hook(print_pressed_keys) keyboard.hook_key("8", print_pressed_keys) ws.run()
def __init__(self): with open("words.txt", 'a', encoding='utf8') as f: f.write(time.strftime("\n\"%Y-%m-%d\":", time.localtime()) + '\n') self.root = Tk() self.root.withdraw() #keyboard.add_hotkey('alt+r', self.read_clip, trigger_on_release=True) keyboard.hook_key('f9', self.read_clip) self.root.mainloop()
def __init__(self): self.burst_sender = None self.is_burst_sending = False self.pre_key_time = 0 keyboard.hook_key('a', self.run_burst_one_key) keyboard.wait('esc')
def main() -> None: settings = get_settings() key_map = get_keymap() board = Board(settings["server_ip"], int(settings["server_port"])) print("[INFO] Binding ...") for key, msg in key_map.items(): callback = partial(board._send_message, message=msg) keyboard.hook_key(key, callback, suppress=True) # keyboard.add_hotkey('p', lambda: print('space was pressed!')) print("[INFO] Running ...") keyboard.wait("0") keyboard.unhook_all() print("[INFO] Stopped")
def regist_hotkey(self, hotkey_group): # keyboard.add_hotkey('esc', self.stop_hotkey_waiting) # key_macro_list = [] for hot_key, key_macro_list in hotkey_group.items(): if self.is_buster_key(key_macro_list): keyboard.hook_key(hot_key, self.burst_one_key) else: keyboard.add_hotkey(hot_key, self.send_hot_key, args=[key_macro_list]) # keyboard.add_hotkey('F2', self.hotkey_fun) # hotkey_listen = utils.CreateEmptyThread(self.thread_queue, 'stop_hotkey') # hotkey_listen.start() # hotkey_listen.join() keyboard.wait('esc')
def play_file(filename, playpause_key=None, delete_mp3=True): # Проверяем существование файлика if os.path.exists(filename): # Подгружаем в плеер и запускаем mixer.music.load(filename) mixer.music.play() # Событие по завершению аудиодорожки mixer.music.set_endevent(SONG_END) # Переменная для цикла is_music_over = False # Play/Пауза pause_key_hook = None if (playpause_key != None): pause_key_hook = keyboard.hook_key(playpause_key, on_pause_down) print(f"hook added on key {playpause_key}") # Ждём... while not is_music_over: # Если вдруг в событиях обнаружится, что... for event in pygame.event.get(): # ... песня закончилась, то ... if event.type == SONG_END: # записываем это и завершаем цикл is_music_over = True time.sleep(0.01) # Останавливаем if (pause_key_hook != None): keyboard.unhook_key(pause_key_hook) print("hook removed") mixer.music.stop() time.sleep(0.01) # Удаляем файл по окончанию, если надо if (delete_mp3) and (os.path.exists(filename)): os.remove(filename) time.sleep(0.01)
def register_hotkey(self): self.deregister_hotkey() # register key hooks for logging based on hotkey + steps if self.modifier: keyboard.add_hotkey( self.modifier + '+' + self.hotkey, \ self.hotkey_pressed) else: keyboard.hook_key( self.hotkey, \ lambda: self.hotkey_pressed() ) logging.debug( "Hotkey {} registered for {}".format( \ self.hotkey, \ self.name) )
def start_replay_recorder(): global started started = True while started: play_layer = game_manager.get_play_layer() level = play_layer.get_level_settings().get_level() level_type = level.get_level_type() scene = game_manager.get_scene() if scene == Scene.EDITOR_OR_LEVEL or scene == Scene.OFFICIAL_LEVEL: play_layer = game_manager.get_play_layer() if play_layer.dead or play_layer.percent == 0.0 or play_layer.is_null( ) or play_layer.percent >= 100 or playing_replay: continue if level_type != LevelType.SAVED: if level_type != LevelType.EDITOR: if level_type != LevelType.OFFICIAL: continue if play_layer.percent > 0: start_time = time() print("Recording...") recent = record_input() print("Done") if play_layer.get_percent() >= 100: def export(key): print("Exporting replay") file.pack_replay_file( recent, f"{user_name} - {level.creator_name} - {level.name}.gdr" ) try: keyboard.unhook("f2") except KeyError: pass def back(key): try: keyboard.unhook("f2") except KeyError: if not playing_replay: pass keyboard.hook_key("f2", export, True) keyboard.hook_key("esc", back, False) continue
def test_hook_key(self): self.i = 0 def count(): self.i += 1 keyboard.hook_key("a", keyup_callback=count) self.press("a") self.assertEqual(self.i, 0) self.release("a") self.click("b") self.assertEqual(self.i, 1) keyboard.hook_key("b", keydown_callback=count) self.press("b") self.assertEqual(self.i, 2) keyboard.unhook_key("a") keyboard.unhook_key("b") self.click("a") self.assertEqual(self.i, 2)
def test_hook_key(self): self.i = 0 def count(): self.i += 1 keyboard.hook_key('a', keyup_callback=count) self.press('a') self.assertEqual(self.i, 0) self.release('a') self.click('b') self.assertEqual(self.i, 1) keyboard.hook_key('b', keydown_callback=count) self.press('b') self.assertEqual(self.i, 2) keyboard.unhook_key('a') keyboard.unhook_key('b') self.click('a') self.assertEqual(self.i, 2)
def __init__(self, among_us_memory: AmongUsMemory, audio_engine: AudioEngineBase): self.among_us_memory = among_us_memory self.audio_engine = audio_engine self.closing = False self.ip = None self.voice_port = None self.data_port = None self.client_id = random.getrandbits(64) self.settings = packets.AllSettingsPacket() self.send_data_lock = Lock() self.voice_buffer = None self.encoder = None self.sent_frames_count = 0 self.release_frame = -1 self.release_frame_duration = 10 self.last_memory_read: MemoryRead = None self.imposter_voice = False self.noise_threshold = 100 keyboard.hook_key("shift", self.on_shift) keyboard.on_press_key(29, self.on_right_ctrl) self.muted = False self.voice_socket = None self.udp_data_socket = None self.command_map = { 'help': self.help_command, 'exit': self.exit_command, 'retry': self.retry_command, 'volume': self.volume_command, 'mute': self.mute_command, 'threshold': self.threshold_command, 'release': self.release_command, } self.packet_handlers = { packets.SettingPacket: self.setting_packet_handler, packets.ServerRestartingPacket: self.retry_command, }
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 __register_hotkey(self, hotkey, callback, scope='intro'): if isinstance(hotkey, str): hotkey = scctool.settings.config.loadHotkey(hotkey) if not hotkey['name']: return if hotkey['scan_code'] == 0: return value = keyboard.hook_key( hotkey['scan_code'], lambda e, hotkey=hotkey: self.__callback_on_hook( hotkey['scan_code'], hotkey['is_keypad'], e, callback)) self.hooked_keys[scope].add(value)
def hook_hotkey(self, hotkey=None): if hotkey is None: if self.key is None: raise Exception("Please provide a hotkey for the macro.") else: hotkey = self.key # Do nothing if we're already hooked if self.hotkey_hook is None: Macro.key_macro_count[hotkey] = Macro.key_macro_count.get( hotkey, 0) + 1 self.hotkey_hook = keyboard.hook_key(hotkey, self.__action, self.suppress)
def test_hook_key_nonblocking(self): self.i = 0 def count(event): self.i += 1 hook = keyboard.hook_key('A', count) self.do(d_a) self.assertEqual(self.i, 1) self.do(u_a+d_b) self.assertEqual(self.i, 2) self.do([make_event(KEY_DOWN, 'A', -1)]) self.assertEqual(self.i, 3) keyboard.unhook_key(hook) self.do(d_a) self.assertEqual(self.i, 3)
def test_hook_key_blocking(self): self.i = 0 def count(event): self.i += 1 return event.scan_code == 1 hook = keyboard.hook_key('A', count, suppress=True) self.do(d_a, d_a) self.assertEqual(self.i, 1) self.do(u_a+d_b, u_a+d_b) self.assertEqual(self.i, 2) self.do([make_event(KEY_DOWN, 'A', -1)], []) self.assertEqual(self.i, 3) keyboard.unhook_key(hook) self.do([make_event(KEY_DOWN, 'A', -1)], [make_event(KEY_DOWN, 'A', -1)]) self.assertEqual(self.i, 3)
def start_hotkeys(self): obs_settings = self.app.settings.hotkeys.obs kivy_settings = self.app.settings.hotkeys.kivy general_settings = self.app.settings.hotkeys.general # Camera Hotkey keyboard.hook_key(obs_settings.camera_scene_hotkey[0], lambda x: self.on_hotkey("camera", x), suppress=True) Logger.info("binding hotkey " + f"{obs_settings.camera_scene_hotkey[0]}") # Center Scene Hotkey keyboard.hook_key(obs_settings.center_screen_hotkey[0], lambda x: self.on_hotkey("center", x), suppress=True) Logger.info("binding hotkey" + f" {obs_settings.center_screen_hotkey[0]}") # Automatic Checkbox Hotkey keyboard.add_hotkey(kivy_settings.scene_lock, lambda x: self.on_hotkey("scene_lock", x), suppress=True) Logger.info(f"binding hotkey {kivy_settings.scene_lock}") # Next Button for the clicker keyboard.on_release_key(general_settings.clicker_forward, lambda x: self.on_hotkey("clicker_next", x), suppress=True) Logger.info(f"binding hotkey {general_settings.clicker_forward}") # Previous Button for the clicker keyboard.on_release_key(general_settings.clicker_backward, lambda x: self.on_hotkey("clicker_prev", x), suppress=True) Logger.info("binding hotkey " + f"{general_settings.clicker_backward}")
def callback(hotkey): # try to remove the previously set hotkey if there is one. try: keyboard.unhook_key(hotkey) # KeyError was coming up when loading the program and # the lineEdit area was empty (no hotkey set), then you # set one, reload the setting once back to blank works, # but if you click reload settings again, it errors # we can just have it pass, but don't want to throw in # generic exception here in case another one of these # pops up somewhere. except (AttributeError, KeyError): pass # wait until user presses the hotkey, then keyboard module reads the input key_name = __get_key_name(keyboard.read_event(True)) try: # If the key the user presses is equal to itself or another hotkey already set, # this causes issues. so here, it catches that, and will make no changes to the hotkey. # or # keyboard module allows you to hit multiple keys for a hotkey. they are joined # together by +. If user hits two keys at the same time, make no changes to the # hotkey. A try and except is needed if a hotkey hasn't been set yet. I'm not # allowing for these multiple-key hotkeys because it can cause crashes, and # not many people are going to really use or need this. if __is_key_already_set(self, key_name) or (key_name != '+' and '+' in key_name): self.afterSettingHotkeySignal.emit() return except AttributeError: self.afterSettingHotkeySignal.emit() return # add the key as the hotkey, set the text into the LineEdit, set it as old_xxx_key, # then emite a signal to re-enable some buttons and change some text in GUI. # We need to inspect the event to know if it comes from numpad because of _canonial_names. # See: https://github.com/boppreh/keyboard/issues/161#issuecomment-386825737 # The best way to achieve this is make our own hotkey handling on top of hook # See: https://github.com/boppreh/keyboard/issues/216#issuecomment-431999553 self.split_hotkey = keyboard.hook_key( key_name, lambda e: _hotkey_action(e, key_name, self.startAutoSplitter)) self.splitLineEdit.setText(key_name) self.split_key = key_name self.afterSettingHotkeySignal.emit()
def test_hook_key_nonblocking(self): self.i = 0 def count(event): self.i += 1 hook = keyboard.hook_key('A', count) self.do(d_a) self.assertEqual(self.i, 1) self.do(u_a + d_b) self.assertEqual(self.i, 2) self.do([make_event(KEY_DOWN, 'A', -1)]) self.assertEqual(self.i, 3) keyboard.unhook_key(hook) self.do(d_a) self.assertEqual(self.i, 3)
def test_hook_key_blocking(self): self.i = 0 def count(event): self.i += 1 return event.scan_code == 1 hook = keyboard.hook_key('A', count, suppress=True) self.do(d_a, d_a) self.assertEqual(self.i, 1) self.do(u_a + d_b, u_a + d_b) self.assertEqual(self.i, 2) self.do([make_event(KEY_DOWN, 'A', -1)], []) self.assertEqual(self.i, 3) keyboard.unhook_key(hook) self.do([make_event(KEY_DOWN, 'A', -1)], [make_event(KEY_DOWN, 'A', -1)]) self.assertEqual(self.i, 3)
def callback(hotkey): try: keyboard.unhook_key(hotkey) except (AttributeError, KeyError): pass key_name = __get_key_name(keyboard.read_event(True)) try: if __is_key_already_set(self, key_name) or (key_name != '+' and '+' in key_name): self.afterSettingHotkeySignal.emit() return except AttributeError: self.afterSettingHotkeySignal.emit() return self.pause_hotkey = keyboard.hook_key( key_name, lambda e: _hotkey_action(e, key_name, self.startPause)) self.pausehotkeyLineEdit.setText(key_name) self.pause_key = key_name self.afterSettingHotkeySignal.emit()
from misc_scripts.image_template_matching import get_matches_from_screen from time import sleep # globals stop = False STOP_BUTTON = 'F2' # constant def toggle_stop(): global stop stop = not stop print('stop = {}'.format(stop)) # stop hotkey keyboard.hook_key('F2', keydown_callback=toggle_stop) def record_mouse_events(): sleep(1.5) stop_record = 'right' print('Mouse recording has begun') print('Press {} mouse button to stop mouse recording'.format(stop_record)) events = mouse.record(button=stop_record) print('Recorded:\n{}'.format(pformat(events))) return events def get_number_of_iterations(): question = 'Enter number of times to loop playback of recorded events: '
def test_hook_key_invalid(self): with self.assertRaises(ValueError): keyboard.hook_key('invalid', lambda e: None)
if __name__ == '__main__': from configurations import * import keyboard import drag drag_thread = drag.Drag() trigger_key_down = True def trigger_key_event_detected(event: keyboard.KeyboardEvent): global drag_thread, trigger_key_down if event.event_type == "down" and not trigger_key_down and \ (TRIGGER_MODIFIERS == "" or keyboard.is_pressed(TRIGGER_MODIFIERS)): # Second condition is to handle repeated key events that reports as multiple "down" events trigger_key_down = True drag_thread.start() elif event.event_type == "up": drag_thread.stop() drag_thread = drag.Drag() trigger_key_down = False keyboard.hook_key(TRIGGER_KEY, trigger_key_event_detected) keyboard.wait()
def loadSettings(self: AutoSplit, load_settings_on_open: bool = False, load_settings_from_livesplit: bool = False): if load_settings_on_open: settings_files = [] for file in os.listdir(auto_split_directory): if file.endswith(".pkl"): settings_files.append(file) # find all .pkls in AutoSplit folder, error if there is none or more than 1 if len(settings_files) < 1: error_messages.noSettingsFileOnOpenError() self.last_loaded_settings = None return elif len(settings_files) > 1: error_messages.tooManySettingsFilesOnOpenError() self.last_loaded_settings = None return else: self.load_settings_file_path = os.path.join( auto_split_directory, settings_files[0]) elif not load_settings_on_open and not load_settings_from_livesplit: self.load_settings_file_path = QtWidgets.QFileDialog.getOpenFileName( self, "Load Settings", os.path.join(auto_split_directory, "settings.pkl"), "PKL (*.pkl)")[0] if self.load_settings_file_path == '': return try: with open(self.load_settings_file_path, 'rb') as f: settings: List[Union[str, int]] = pickle.load(f) settings_count = len(settings) if settings_count < 18: if not load_settings_from_livesplit: error_messages.oldVersionSettingsFileError() return # v1.3-1.4 settings. Add default pause_key and auto_start_on_reset_setting if settings_count == 18: settings.insert(9, '') settings.insert(20, 0) # v1.5 settings elif settings_count != 20: if not load_settings_from_livesplit: error_messages.invalidSettingsError() return self.last_loaded_settings = [ self.split_image_directory, self.similarity_threshold, self.comparison_index, self.pause, self.fps_limit, self.split_key, self.reset_key, self.skip_split_key, self.undo_split_key, self.pause_key, self.x, self.y, self.width, self.height, self.hwnd_title, _, _, self.group_dummy_splits_undo_skip_setting, self.loop_setting, self.auto_start_on_reset_setting ] = settings except (FileNotFoundError, MemoryError, pickle.UnpicklingError): # HACK / Workaround: Executing the error QMessageBox from the auto-controlled Worker Thread makes it hangs. # I don't like this solution as we should probably ensure the Worker works nicely with PyQt instead, # but in the mean time, this will do. if not load_settings_from_livesplit: error_messages.invalidSettingsError() return self.splitimagefolderLineEdit.setText(self.split_image_directory) self.similaritythresholdDoubleSpinBox.setValue(self.similarity_threshold) self.pauseDoubleSpinBox.setValue(self.pause) self.fpslimitSpinBox.setValue(self.fps_limit) self.xSpinBox.setValue(self.x) self.ySpinBox.setValue(self.y) self.widthSpinBox.setValue(self.width) self.heightSpinBox.setValue(self.height) self.comparisonmethodComboBox.setCurrentIndex(self.comparison_index) self.hwnd = win32gui.FindWindow(None, self.hwnd_title) # set custom checkbox's accordingly self.groupDummySplitsCheckBox.setChecked( self.group_dummy_splits_undo_skip_setting == 1) self.loopCheckBox.setChecked(self.loop_setting == 1) self.autostartonresetCheckBox.setChecked( self.auto_start_on_reset_setting == 1) self.autostartonresetCheckBox.setChecked( self.auto_start_on_reset_setting == 1) # TODO: Reuse code from hotkeys rather than duplicating here # try to set hotkeys from when user last closed the window try: keyboard.unhook_key(self.split_hotkey) # pass if the key is an empty string (hotkey was never set) except (AttributeError, KeyError): pass try: self.splitLineEdit.setText(self.split_key) if not self.is_auto_controlled: self.split_hotkey = keyboard.hook_key( self.split_key, lambda e: _hotkey_action( e, self.split_key, self.startAutoSplitter)) except (ValueError, KeyError): pass try: keyboard.unhook_key(self.reset_hotkey) except (AttributeError, KeyError): pass try: self.resetLineEdit.setText(self.reset_key) if not self.is_auto_controlled: self.reset_hotkey = keyboard.hook_key( self.reset_key, lambda e: _hotkey_action(e, self.reset_key, self.startReset)) except (ValueError, KeyError): pass try: keyboard.unhook_key(self.skip_split_hotkey) except (AttributeError, KeyError): pass try: self.skipsplitLineEdit.setText(self.skip_split_key) if not self.is_auto_controlled: self.skip_split_hotkey = keyboard.hook_key( self.skip_split_key, lambda e: _hotkey_action( e, self.skip_split_key, self.startSkipSplit)) except (ValueError, KeyError): pass try: keyboard.unhook_key(self.undo_split_hotkey) except (AttributeError, KeyError): pass try: self.undosplitLineEdit.setText(self.undo_split_key) if not self.is_auto_controlled: self.undo_split_hotkey = keyboard.hook_key( self.undo_split_key, lambda e: _hotkey_action( e, self.undo_split_key, self.startUndoSplit)) except (ValueError, KeyError): pass try: keyboard.unhook_key(self.pause_hotkey) except (AttributeError, KeyError): pass try: self.pausehotkeyLineEdit.setText(self.pause_key) if not self.is_auto_controlled: self.pause_hotkey = keyboard.hook_key( self.pause_key, lambda e: _hotkey_action(e, self.pause_key, self.startPause)) except (ValueError, KeyError): pass self.last_successfully_loaded_settings_file_path = self.load_settings_file_path self.checkLiveImage()
print("") for mimsy in time_mappings.keys(): print(mimsy + ": " + str(now - time_mappings.get(mimsy)) + " seconds since last update") if show_raw: print("Showing NATIVE angle data.") else: print("Showing RELATIVE angle data.") for mimsy in init_angles.keys(): print("Offset Angles for " + mimsy + ": roll=" + str(init_angles[mimsy][0]) + " | pitch=" + str(init_angles[mimsy][1])) if reset_flag: print("Reset Buffer (size=" + str(len(reset_buf)) + ", missing=" + str(len(network)-len(reset_buf)) + "): " + str(reset_buf)) else: print("Reset flag not set.") print("") keyboard.hook_key('r', lambda event: reset(event), suppress=False) keyboard.hook_key('n', lambda event: toggleRaw(event), suppress=False) keyboard.hook_key('q', lambda event: brk(event), suppress=False) keyboard.hook_key('u', lambda event: consoleUpdate(event), suppress=False) while run: try: # wait for a request message, dist_addr = socket_handler.recvfrom(1024) timestamp = time() hisAddress = dist_addr[0] hisPort = dist_addr[1] ASN = struct.unpack('<HHB',message[0:5])
def forward_and_right(): global client client.set_control(1, 0, 0, 1) def image(): global client, img_count img = client.get_image() cv2.imwrite(f'img{img_count}.png', img) img_count += 1 def finish(): global keep_running keep_running = False keyboard.hook_key('w', forward) keyboard.hook_key('a', left) keyboard.hook_key('d', right) keyboard.hook_key('s', backward) keyboard.hook_key('q', forward_and_left) keyboard.hook_key('e', forward_and_right) keyboard.hook_key('i', image) keyboard.hook_key('space', finish) while keep_running: print("Running") time.sleep(0.5) print("Stopped")
def left(): global turn, delta_turn turn -= delta_turn if turn < 0: turn = 0 def right(): global turn, delta_turn turn += delta_turn if turn > 500: turn = 500 def stop(): global speed speed = 250 def reset(): global speed, turn speed = turn = 250 def finish(): global keep_running keep_running = False keyboard.hook_key('up', up) keyboard.hook_key('down', down) keyboard.hook_key('left', left) keyboard.hook_key('right', right) keyboard.hook_key('space', stop) keyboard.hook_key('r', reset) keyboard.hook_key('q', finish) with Vehicle(port, baudrate) as car: while keep_running: time.sleep(0.5) car.move(speed, turn) print(f'Speed: {speed}, turn: {turn}')
def 开始监听大写锁定键(self): keyboard.hook_key('caps lock', self.大写锁定键被触发)
def init_master(self): keyboard.hook_key(key=self.master, callback=self.masterpress, suppress=True)
keyboard.press_and_release("space") while True: play_layer = game_manager.get_play_layer() if play_layer.percent > 0: sleep(1.5) if data: play_input(data) else: play_input(recent) print("Done playing") break if not data: playing_replay = False keyboard.hook_key("f1", play_replay, True) def play_replay_file(replayname): play_replay(None, file.unpack_replay_file(replayname)) def start_replay_recorder(): global started started = True while started: play_layer = game_manager.get_play_layer() level = play_layer.get_level_settings().get_level() level_type = level.get_level_type() scene = game_manager.get_scene() if scene == Scene.EDITOR_OR_LEVEL or scene == Scene.OFFICIAL_LEVEL: