def click(time_pre_up, passwd, deley): a = keyboard.read_event() if a.event_type == "down": t = time.time() b = keyboard.read_event() while not b.event_type == "up" and b.name == a.name: b = keyboard.read_event() time_up = time.time() wait_time = t - time_pre_up if len(passwd) != 0: deley.append(wait_time) passwd.append(a.name) return time_up, passwd, deley
def config(): #execute configuration print(bcolors.GREEN + "\nInitializing configuration procedure .", end="", flush=True) #Fancy startup stuff. Prolly going to remove it time.sleep(0.5) print(".", end="", flush=True) time.sleep(0.5) print(".", flush=True) time.sleep(0.5) print(bcolors.RESET) #Create the folder for the configurations, if it it doesen't exist Path("/etc/EasyKeyboardManager/").mkdir(parents=True, exist_ok=True) outfile = open("/etc/EasyKeyboardManager/config.txt", "w") #actual configuration print("Press any key on your " + bcolors.YELLOW + "MAIN" + bcolors.RESET + " keyboard") ev = keyboard.read_event(suppress=False) #double to capture the press AND the release ev = keyboard.read_event(suppress=False) mainK = ev.device print("\nSaving " + bcolors.YELLOW + mainK + bcolors.RESET + " as MAIN keyboard") time.sleep(0.5) print("\n\nPress any key on your " + bcolors.RED + "MACRO" + bcolors.RESET + " keyboard") ev = keyboard.read_event(suppress=False) #double to capture the press AND the release ev = keyboard.read_event(suppress=False) macroK = ev.device print("\nSaving " + bcolors.RED + macroK + bcolors.RESET + " as MACRO keyboard") #write the file outfile.write("MAIN:=:" + mainK + "\n") outfile.write("MACRO:=:" + macroK) outfile.close() print("\nConfig file saved in /etc/EasyKeyboardManager/config.txt" + bcolors.GREEN + "\nConfiguration procedure complete.\n" + bcolors.RESET) #Flush stdin to prompt a clear terminal time.sleep(0.5) tcflush(sys.stdin, TCIOFLUSH)
def record(start='Ctrl + F3'): macro = Macro() try: print('Waiting for %s to start...' % start) keyboard.wait(start) print('Start recording. ') print('Tip: press \\ for special operations or end recording. ') mouse.hook(macro.appendMouse) while True: op = keyboard.read_event() if op.name == '\\': help = '\\ : \\, t : sleep, esc : stop' print(help, end='\r', flush=True) opUp = passKeyUp(op) superKey = keyboard.read_event() print(' ' * len(help), end='\r') passKeyUp(superKey) if superKey.name == '\\': print('\\') macro.append(Action(getPos(), key=op)) macro.append(Action(getPos(), key=opUp)) elif superKey.name == 't': print('Sleep') macro.append(Sleep(macro.default_interval)) elif superKey.name == 'esc': mouse.unhook(macro.appendMouse) print('End') try: try: while macro[0].key.name in start.lower( ) and macro[0].key.event_type == 'up': macro.pop(0) except AttributeError: pass except IndexError: pass record.last = macro return macro else: print('Invalid super key. ', ' ' * 6) elif 'win' in op.name: print('Sorry, Windows key is reserved for Failsafe. ') else: if op.event_type == 'down': print(op.name) macro.append(Action(getPos(), key=op)) except MismatchError: return None
def capture_keys(queue): print("Ctrl-ESC to exit!") all_keys = np.zeros(128, dtype=np.float32) running = True # stash current state current_state = keyboard.stash_state() # ctrl-esc exit_seq = on_sequence([29, 1]) while running: k = keyboard.read_event(True) if k.scan_code < len(all_keys) and k.scan_code >= 0: if k.event_type == "up" and all_keys[k.scan_code] != 0: all_keys[k.scan_code] = 0.0 if k.event_type == "down" and all_keys[k.scan_code] != 1: all_keys[k.scan_code] = 1.0 if exit_seq(k.scan_code): running = False queue.put((all_keys.tobytes(), k.time, k.name)) keyboard.restore_state(current_state) time.sleep(0.05) keyboard.restore_state(current_state) queue.put(None) keyboard.restore_state(current_state)
def run(self): """ - zapisuje aktualny input klawiatury do zmiennej globalnej - wymaga ustawienia input_enable na True na początku i na False na końcu :return: """ hotkey_press = {'shift': False, 'alt': False, 'backspace': False} while True: event = str(read_event()) if 'alt' in event: hotkey_press['alt'] = True if 'down' in event else False continue if 'shift' in event: hotkey_press['shift'] = True if 'down' in event else False continue if 'backspace' in event and 'down' in event: self.current_input = self.current_input[:-1] if len( self.current_input) >= 1 else '' if 'enter' in event and 'down' in event: self.finish = True break pocz = event.find('(') end = event.find(')') event = event[pocz + 1:end] event = event.split(' ') if len(event) == 2: event, action = event if len(event) == 1 and action == 'down': out = event if hotkey_press['alt']: out = self.letter_alt.get(out, out) if hotkey_press['shift']: out = out.capitalize() self.current_input += out
def run(self): self.root.update_idletasks() print('# --------------------') print(f'Deciding About picture nr. {pic_ix + 1}: {this_pic_source}:') for this_mapping in key_mappings: print(f' {this_mapping} -> {key_mappings[this_mapping]}') print(' b -> go back one image') print(' a -> apply changes and quit') print(' q -> quit without applying changes') await_input = True while await_input: key = keyboard.read_event() if key.event_type == 'up': key = None elif key.name in key_mappings.keys() or\ key.name in ['a', 'q', 'b']: self.captured_key = key.name await_input = False else: print('No function attached to this key.') self.root.quit() self.root.update_idletasks()
def _start_listening(self): """ Listen to keypresses until 'esc' is pressed. """ while self._esc_trigger: self._key_pressed = keyboard.read_event() self._log_event(self._key_pressed)
def resize(prompt, key_in, x_, y_): full_scr = 0 print(prompt) x, y = x_, y_ while True: event = keyboard.read_event() if event.event_type == keyboard.KEY_DOWN: key = event.name if key == key_in: break elif key == 'down': y += 1 set_mod(x, y) elif key == 'up': y -= 1 set_mod(x, y) elif key == 'right': x += 1 set_mod(x, y) elif key == 'left': x -= 1 set_mod(x, y) elif key == 'f11' or 'alt+enter': if full_scr == 0: print('Внимание! Вы вышли в полноэкранный режим!') full_scr = 1 else: set_mod(x, y) full_scr = 0 else: pass return x, y
def make_cooltext(is_uppercase_turn=False): #wait for them to press a key and then record that event key = keyboard.read_event(suppress=True) name = key.name #If they are not pressing down a key, then we should just ignore the event if key.event_type != "down": return make_cooltext(is_uppercase_turn=is_uppercase_turn) if name == "esc": #If they press the escape key, then they want to stop doing the #Cooltext. Once they press the escape buttton, it will recurse #the main funciton, and will again wait for the key combination return main() if len(name) != 1: #any time that the length is longer than one it is a special key #We should stil send special keys as well, because they cannot have #an uppercase version. keyboard.send(name) return make_cooltext(is_uppercase_turn=is_uppercase_turn) #write the uppercase version of the letter if it is an alternate keypress keyboard.write(name.upper() if is_uppercase_turn else name) #toggle the boolean value return make_cooltext(is_uppercase_turn=not is_uppercase_turn)
def main(): print('ClicKeys clackering') while True: key = keyboard.read_event() # print('{0}: {1}'.format(key.event_type, key.name)) key_pressed(key)
def spec_input(prompt, hist_list): ''' This procedure prompts the user with "prompt", and reads characters until <enter>. It also recognizes the arrow keys and in response, allows the user to scroll through the history and select or edit one of them. The return value is the user input (either by typing or history lisy) ''' spec_keys = [ 'up', 'down', 'right', 'left', 'esc', 'enter', 'delete', 'backspace' ] spec_key = True user_inp = '' hist_dx = len(hist_list) #Pointer to history entr to display # print(prompt, end='') print(prompt) while spec_key: key = kb.read_key( ) #This triggers/unblocks on the downpress of any key next = kb.read_event() #Finish thge keypress--wait for release of key # print('\n\n*** YOU PRESSED "{}"; ASCII = {}\n'.format(key,ord(key))) # print('\n\n*** YOU PRESSED "{}, LENGTH = {}"\n'.format(key, len(key))) if key == "enter": user_inp = user_inp + key else: spec_key = key in spec_keys if not spec_key: continue elif key == "up": hist_dx = maximum(0, hist_dx - 1) #Decement with 0 as min user_inp = hist_list[hist_dx] elif key == "down": hist_dx = minimum(len(hist_list), hist_dx + 1) #Decement with 0 as min user_inp = hist_list[hist_dx] elif key == "left": pass #Not implemented yet elif key == "right": pass #Not implemented yet elif key == "esc": pass #Not implemented yet elif key == "delete": pass #Not implemented yet elif key == "backspace": pass #Not implemented yet else: pass #Not implemented yet # hist_list.append(user_inp) return (user_inp)
def passKeyUp(keyDown): try: assert keyDown.event_type == 'down' keyUp = keyboard.read_event() assert keyUp.name == keyDown.name and keyUp.event_type == 'up' return keyUp except AssertionError: print('\nError: mismatch:', keyDown, 'and', keyUp) raise MismatchError
def main(): try: while True: event = keyboard.read_event() handleEvent(event) except KeyboardInterrupt: pass finally: clearTempFile()
def key_pressed(prompt, *key_in): print(prompt) while True: event = keyboard.read_event() if event.event_type == keyboard.KEY_DOWN: key = event.name if key in key_in: break return key
def game_loop_learn(screen=None, player_nick=None): """ # Karol #czyści okno i rysuje swoje wyswietla litery wykorzystuje choose_letter jak jest poprawna podaje kolejną a jak nie to czeka aż będzie enter przerywa grę :return: None """ # Inicjalizacja, wartosci Pomocnicze white = (255, 255, 255) screen.fill(white) char = choose_letter() letter = '' font = pygame.font.Font('freesansbold.ttf', 70) start = True while True: if start is False: event = str(read_event()) else: event = '' start = False if 'down)' in event: if 'esc' in event: return None if len(event[event.find('(') + 1:event.find(' ')]) == 1: letter = event[event.find('(') + 1:event.find(' ')] if letter == char: char = choose_letter() # for event in pygame.event.get(): # if event.type == pygame.KEYDOWN: # # if event.key == 13: # # sys.exit(0) # letter = Keyborder.code2letter[event.key] # if letter == char: # char = choose_letter() # Rysowanie pygame.display.update() screen.fill(white) # Litera Wylosowana tekst = font.render("NACIŚNIJ> " + char, True, (0, 0, 0)) tekst_prost = tekst.get_rect() tekst_prost.center = (600, 163) screen.blit(tekst, tekst_prost) # Litera Wpisana tekst1 = font.render(letter, True, (0, 0, 0)) tekst1_prost = tekst1.get_rect() tekst1_prost.center = (600, 325) screen.blit(tekst1, tekst1_prost) font_b = pygame.font.Font('freesansbold.ttf', 50) back = font_b.render("Powrót (ESC)", True, (0, 0, 0), (255, 255, 255)) screen.blit(back, (870, 595)) pygame.display.flip()
def color_selector(self): """ allows user to move the cursor to select a color """ option = 0 show = True self.color_op(option) maxi = len(Color) - 1 # amount of colors sel = False while True: # read event and parse it event = keyboard.read_event(suppress=True) tipo = event.event_type key = event.name if tipo == "down": # movement to the left if key == "left": if option <= 0: # no change show = False else: option -= 1 show = True sel = True elif key == "right": if option >= maxi: # no change show = False else: option += 1 show = True sel = True elif key == "esc": exit() elif key == "enter": # update selected color new_color = color.get_color_at_index(option) if self.option != new_color: self.option = new_color self.game.player.score = 1 return else: continue if show: # reprint color options Terminal.up_n_lines(1) self.color_op(option)
def __record(self): event = keyboard.read_event() self.hotkeyData['scan_code'] = event.scan_code self.hotkeyData['is_keypad'] = event.is_keypad self.hotkeyData['name'] = event.name if event.is_keypad: self.hotkeyData['name'] = "num " + self.hotkeyData['name'] self.hotkeyData['name'] = self.hotkeyData['name'].upper().replace( "LEFT ", '').replace("RIGHT ", '') self.thread.deactivateTask('hotkey')
def show_Menu(): pImage = ["arrow_left.jpg", "arrow_left_up.jpg", "arrow_top.jpg"] always = 0 while always == 0: print("Waiting for press!") test = keyboard.read_event() print(test.name) if test.name == '6': # idx = keyboard.read_event() # print(int(idx.name)) # startScanning(pImage, idx.name) try: idx = keyboard.read_event() print(int(idx.name)) startScanning(pImage, idx.name) except: print("what?") elif test.name == 'esc': pass
def generate_events(self): while True: if keyboard.is_pressed("ctrl+shift+e"): exit() elif keyboard.is_pressed("ctrl+shift+s"): self.save() logging.warning("returned") # elif keyboard.is_pressed("ctrl+shift+p"): # send_to_server() else: yield keyboard.read_event()
def generate_events(): while True: if keyboard.is_pressed('ctrl+shift+e'): exit() elif keyboard.is_pressed('ctrl+shift+s'): global data save() logging.warning("returned") elif keyboard.is_pressed('ctrl+shift+p'): send_to_server() else: yield keyboard.read_event()
def wait_for_keypress(suppress=False): """ Waits for any key to be pressed TODO: Add timeout keyword to wait_for_keypress when keyboard.read_event can accept same keyword to allow user to press any key and end the method immediately """ while True: key_event = keyboard.read_event() if key_event.event_type == 'up': break
def main(): prev = False while True: print("\n\n\n\n\n\n") keypressed = "select point" while keypressed != 70: keypressed = keyboard.read_event().scan_code keyboard.read_event() if keypressed==71: prev=not(prev) print("save range set to "+ str(prev)) if prev: print("old range") else: print("new session") box=getBoxRange() text=itt_OCR(imagePostPro(rangeScreenshot(box))) try: playGTTS(text) except AssertionError: pass
def listen_key(): global tone_flag, rec_flag, record, interval, start_time, tone_name_list, ten_sec_flag, old_tone while True: key = keyboard.read_event() if key.event_type == 'up': key = key.name # change the instrument if key >= '0' and key <= '9': print("change") new_tone = int(key) - 1 if new_tone == old_tone or (new_tone + 1) > len(tone_name_list): continue else: tone_flag = new_tone old_tone = new_tone print("Instruments Changed to:", tone_name_list[tone_flag]) # start/stop recording elif key == 'r': if rec_flag == 1: record = np.zeros(shape=[441000, 2], dtype=np.int16) print("record start!") noti_rec_start.play(0) start_time = time.time() rec_flag = rec_flag * (-1) elif rec_flag == -1: noti_rec_stop.play(0) print("saving...") zero_num = 0 i = 1 try: while True: if (record[len(record) - i] == record[0]).any(): zero_num += 1 i += 1 else: break record = record[:len(record) - 1 - zero_num] except: print("Empty record!") continue now = time.time() now_time = time.strftime("%Y%m%d_%H%M%S") path = (now_time + ".wav") wavfile.write(path, 44100, record) print("local saved!") rec_flag = rec_flag * (-1) else: continue
def mode_selector() -> str: """ allows the user to select the game mode """ selection = 0 show = True # clear screen before mode selection Terminal.clear() print("Welcome to the Tile Game!") Terminal.print_modes(selection) while True: # read user event event = keyboard.read_event(suppress=True) key = event.name tipo = event.event_type # print(key, tipo) if tipo == "down" and key == "down": if selection >= 2: # print(selection) show = False else: selection += 1 show = True elif tipo == "down" and key == "up": if selection <= 0: # print(selection) show = False else: selection -= 1 show = True elif tipo == "down" and key == "enter": if selection == 0: # exit the game exit() elif selection == 1: # enable name mode return TERMINAL elif selection == 2: return WINDOW show = False return elif tipo == "down" and key == "esc": exit() if show: Terminal.up_n_lines(3) Terminal.print_modes(selection)
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 keyboard_val_gen(): key_status = { 'w': False, 'a': False, 's': False, 'd': False, 'up': False, 'down': False } while True: event = keyboard.read_event() if key_status.get(event.name) is not None: if event.event_type == "up": key_status[event.name] = False else: key_status[event.name] = True left = 100 right = 100 ladder = 100 if key_status['s']: left += 100 right += 100 if key_status['w']: left -= 100 right -= 100 if key_status['d']: left -= 100 right += 100 if key_status['a']: left += 100 right -= 100 if key_status['up']: ladder += 100 if key_status['down']: ladder -= 100 left = max(left, 0) left = min(left, 200) right = max(right, 0) right = min(right, 200) ladder = max(ladder, 0) ladder = min(ladder, 200) yield jetsonrpc_pb2.MotorCmd( values=encode_values(left, right, 100, 100, 100, 1))
def _shortcutButtonClick(self): """ Shortcut button click event """ QMessageBox.information( self._view, "", _("Close this message and press a key or key combination. ")) key = keyboard.read_hotkey(True) if key == 'unknown': QMessageBox.information(self._view, "", _("Press again.")) key = keyboard.read_event(True) self._view.shortcutEdit.setText(str(key.scan_code)) else: self._view.shortcutEdit.setText(key)
def run(self): '''Background thread listening to for keyboard events''' while True: key = keyboard.read_event(suppress=True) if key.name == 'esc': self.run_cmd('all_stop') if key.name == '7': cmd = voice_command() if cmd: self.run_cmd(cmd) if key.name in self.commands: if key.event_type == 'down': # on press self.run_cmd(self.commands[key.name][0]) elif key.event_type == 'up': # on release self.run_cmd(self.commands[key.name][1])
def KeyboardListen(cont,env): esc = False amount = 1 while not esc: key = keyboard.read_event() if key.name == 'esc': esc = True if key.name == 'up': cont.addTarget(2,amount) if key.event_type == 'up': cont.stop(2) if key.name == 'down': cont.addTarget(2,-amount) if key.event_type == 'up': cont.stop(2) if key.name == 'left': cont.addTarget(0,-amount) if key.event_type == 'up': cont.stop(0) if key.name == 'right': cont.addTarget(0,amount) if key.event_type == 'up': cont.stop(0) if key.name == 'w': cont.addTarget(1,amount) if key.event_type == 'up': cont.stop(1) if key.name == 's': cont.addTarget(-amount) if key.event_type == 'up': cont.stop(1) if key.name == 'y': cont.addYaw_target(2*amount) if key.event_type == 'up': cont.stop() if key.name == 'x': cont.addYaw_target(-2*amount) if key.event_type == 'up': cont.stop() if key.name == 'q': env.reset() cont.reset()
def get_key_press(): """ Waits for and returns the name of a key release event Note: Using event_type 'up' here to only return the event name when a key is released, otherwise we end up getting duplicate events when a key is pressed and released. I felt waiting for release will feel more correct than triggering the event when the key is pressed. Returns: string -- Name of the key that has been released """ while True: key_event = keyboard.read_event(suppress=False) ## only capture key events when key is released. This prevents ## a second key name event from being captured if key_event.event_type == 'up': # need to convert key_event.name to lowercase to avoid the event # handler being non-responsive if caps-lock is on return str(key_event.name).lower()
def process(): queue.put(keyboard.read_event(suppress=True))