def __init__(self): Thread.__init__(self) self.daemon = True kl = KeyboardListener() ml = MouseListener() self.start() with KeyboardListener(on_press=self.on_press, on_release=self.on_release) as listener: listener.join()
def draw_image(region: Region, color_location: Dict[Color, Location]): terminated = False colors = color_location.keys() print(color_header("Drawing Image")) print("Be sure to select the smallest brush for best quality.") def detect(key): nonlocal terminated if key == Key.esc: terminated = True return False def distance(c1, c2): (r1, g1, b1) = c1 (r2, g2, b2) = c2 return sqrt((r1 - r2)**2 + (g1 - g2)**2 + (b1 - b2)**2) with KeyboardListener(on_press=detect): image_file = input( color_option("Location of the image file to draw: ")) print("Don't move your mouse!") print("Press ESC at any time to cancel.") image = Image.open(image_file) image = image.resize((width := int(region[2] / 5), width))
def run(self): with MouseListener(on_move=self.on_move, on_click=self.on_click, on_scroll=self.on_scroll) as m_listener,\ KeyboardListener(on_press=self.on_press) as k_listner: k_listner.join() m_listener.join()
def start_listeners(): with MouseListener(on_click=on_click, on_scroll=on_scroll, on_move=on_move) as m_listener: with KeyboardListener(on_press=on_press, on_release=on_release) as k_listener: m_listener.join() k_listener.join()
def highlight_region(region: Region): (offset_x, offset_y, diamater) = region radius = diamater / 2 terminated = False print(color_header("Highlighting Region")) print("Press ESC at any time to cancel.") def detect(key): nonlocal terminated if key == Key.esc: terminated = True return False with KeyboardListener(on_press=detect): mouse = MouseController() for deg in range(0, 360): if terminated: break rad = radians(deg) mouse.position = (offset_x + radius + sin(rad) * radius, offset_y + radius + cos(rad) * radius) sleep(0.01) if terminated: print("Highlighting canceled.") else: print("Highlighting finished.")
def listen_event(): def on_click(x, y, button, pressed): # print('{0} {1} at {1}'.format( # button, # 'Pressed' if pressed else 'Released', # (x, y))) if f'{button}' == 'Button.middle' and pressed: print('Button Middle pressed.') tiles = realtime_shot() sync(tiles) # if keyboard.is_pressed('1'): # return False def on_press(key): # print("Key pressed: {0}".format(key)) if key == Key.esc: print("Key pressed: {0}".format(key)) # return False KeyboardListener.stop() MouseListener.stop() keyboard_listener = KeyboardListener(on_press=on_press) mouse_listener = MouseListener(on_click=on_click) keyboard_listener.start() mouse_listener.start() keyboard_listener.join() mouse_listener.join()
def start(self): self._listener_keyboard = KeyboardListener(on_release=self.on_keyboard_release) self._listener_keyboard.start() if input("please input \"MOUSE\" to start mouse function:\n") == "MOUSE": self._listener_mouse = MouseListener(on_click=self.on_click) self._listener_mouse.start() self.ctl_mouse = MouseController()
def listen(self): with MouseListener(on_move=self.on_move, on_click=self.on_click, on_scroll=self.on_scroll) as listener: with KeyboardListener(self.on_press, self.on_release) as listener: listener.join() try: listener.wait() finally: listener.stop()
def await_user_force_stop_the_recording(): print_red_bold("look at the camera, pls.\nstop recording with [ CTRL+C ] or [ ESC ]\n") try: with KeyboardListener(on_press=KeyPress) as keyboard_listener: keyboard_listener.join() except KeyboardInterrupt: pass
def hook_mouse_and_key(self): with MouseListener(on_click=self.mouse_click, on_scroll=self.mouse_scroll, on_move=self.mouse_move) as self.listener: with KeyboardListener( on_press=self.key_press, on_release=self.key_release) as self.listener: self.listener.join()
def listener(): try: with MouseListener(on_click=on_click, on_scroll=on_scroll) as listener: with KeyboardListener(on_release=on_release) as listener: listener.join() except: time.sleep(0.2) print('Error: Do it again!') listener()
def startListening(self): """ Starts Listeners together to avoid AttributeError: CFRunLoopAddSource. """ with MouseListener(on_click=lambda x, y, button, pressed: Machine.on_click(self, x, y, button, pressed)) as listener: with KeyboardListener(on_press=lambda key: Machine.on_press(self, key)) as listener: #The above implementation delays the call to the frame, #allowing the class methods to be altered and replaced by files #externally and thus allowing the parameters to be bled elsewhere. listener.join()
def key_listen(): global kill_threads while not kill_threads: # if current_window == desired_window_name: print('test') with MouseListener(on_move=on_move, on_click=on_click) as listener: with KeyboardListener(on_press=on_press, on_release=on_release) as listener: listener.join()
def ghost_sense(): ''' Detects Mouse/ Keyboard Behaviors ''' if not is_connected(): msg = "Your system is not online. This feature requires internet!" msgbx.showinfo("Connection", msg) return THRESHOLD_VALUE = 30 regex = '^[a-z0-9]+[\._]?[a-z0-9]+[@]\w+[.]\w{2,3}$' if not re.search(regex, email.get()): msgbx.showerror("Ghost Sense", "Receiver's mail address not found!") return else: if not os.path.isdir("./output_img/"): # Make output dir if not present already os.mkdir("output_img") OUTPUT_DIR = "./output_img/" FILE_NAME = datetime.now().strftime("%A %m-%d-%Y_%H:%M:%S") + ".png" msgbx.showinfo("Ghost Sense", "Ghost Sense Activated!") def on_click(x, y, button, pressed): ''' Handles Mouse Events and increase the press count ''' global press_count if pressed: press_count += 1 if press_count > THRESHOLD_VALUE: listener.stop() # Collect mouse events until released def on_press(key): ''' Handles Keyboard Events and increase the press count ''' global press_count try: # print(key.char) press_count += 1 if press_count > THRESHOLD_VALUE: return False except AttributeError: print(key) # Listen for both Mouse and Keyboard events with MouseListener(on_click=on_click) as listener: with KeyboardListener(on_press=on_press) as listener: listener.join() if press_count > THRESHOLD_VALUE: threading.Thread(target=get_action_response, args=()).start() playsound("./assets/bg_music/pred_sense.mp3") capture_img(OUTPUT_DIR, FILE_NAME) threading.Thread(target=send_email, args=[email.get(), OUTPUT_DIR+FILE_NAME]) # print("Sent!") msgbx.showwarning("Ghost Sense", "Unauthorized Access Detected!")
def start(self): with MouseListener( on_move=self.on_move, on_click=self.on_click, on_scroll=self.on_scroll) as listener: with KeyboardListener( on_press=self.on_press, on_release=self.on_release) as listener: listener.join() print("Stopped Recording")
def listen(self): self.server = threading.Thread(target=self.accept_connections) self.keyboard_listener = KeyboardListener(on_press=self.on_press, on_release=self.on_release) self.mouse_listener = MouseListener(on_move=self.on_move, on_click=self.on_click, on_scroll=self.on_scroll) self.keyboard_listener.start() self.mouse_listener.start() self.server.start()
def __init__(self): Thread.__init__(self) self.daemon = True self.start() self.timeCheck = timeChecker() with MouseListener(on_click=self.timeCheck.on_click, on_move=self.timeCheck.on_move, on_scroll=self.timeCheck.on_scroll) as listener: with KeyboardListener( on_press=self.timeCheck.on_press) as listener: listener.join()
def reload_config(self): self.accepted_keys = set() if self.config.alt_modifier: self.accepted_keys.add(Key.alt_l) for key in self.config.key_combination: self.accepted_keys.add(KeyCode.from_char(key)) self.thread = {0: KeyboardListener(on_press=self.on_press, on_release=self.on_release), 1: MouseListener(on_click=self.on_click)}.get(self.config.input_mode) self.mouse_button = {0: Button.x1, 1: Button.x2}.get(self.config.special_mouse_press) self.sequence_length = len(self.config.output_sequence)
def __init__(self, filename): # Setup the listener threads self.keyboard_listener = KeyboardListener(on_press=self.on_press, on_release=self.on_release) self.mouse_listener = MouseListener(on_move=self.on_move, on_click=self.on_click, on_scroll=self.on_scroll) self.count = 0 self.delay = time.time() self.events = [] self.filename = filename
def __init__(self): threading.Thread.__init__(self) self.model=torch.load('model\\test_model100.m',map_location=torch.device('cpu')) self.img_path='data\grab1.png' self.img_dealer_path='data\grab_dealer.png' self.img_player_path='data\grab_player.png' self.model.eval() self.list=[] self.hit=[sg.Text('x'),sg.In(size=(5,1),enable_events=True,key='hit_x'),sg.Text('y'),sg.In(size=(5,1),enable_events=True,key='hit_y'),sg.Radio(text='hit',group_id='check',enable_events=False,key='hit_check')] self.stand=[sg.Text('x'),sg.In(size=(5,1),enable_events=True,key='stand_x'),sg.Text('y'),sg.In(size=(5,1),enable_events=True,key='stand_y'),sg.Radio(text='stand',group_id='check',enable_events=False,key='stand_check')] self.split=[sg.Text('x'),sg.In(size=(5,1),enable_events=True,key='split_x'),sg.Text('y'),sg.In(size=(5,1),enable_events=True,key='split_y'),sg.Radio(text='split',group_id='check',enable_events=False,key='split_check')] self.double=[sg.Text('x'),sg.In(size=(5,1),enable_events=True,key='double_x'),sg.Text('y'),sg.In(size=(5,1),enable_events=True,key='double_y'),sg.Radio(text='double',group_id='check',enable_events=False,key='double_check')] self.deal=[sg.Text('x'),sg.In(size=(5,1),enable_events=True,key='deal_x'),sg.Text('y'),sg.In(size=(5,1),enable_events=True,key='deal_y'),sg.Radio(text='deal',group_id='check',enable_events=False,key='deal_check')] self.extra1=[sg.Text('x'),sg.In(size=(5,1),enable_events=True,key='extra1_x'),sg.Text('y'),sg.In(size=(5,1),enable_events=True,key='extra1_y'),sg.Radio(text='extra1',group_id='check',enable_events=False,key='extra1_check')] self.extra2=[sg.Text('x'),sg.In(size=(5,1),enable_events=True,key='extra2_x'),sg.Text('y'),sg.In(size=(5,1),enable_events=True,key='extra2_y'),sg.Radio(text='extra2',group_id='check',enable_events=False,key='extra2_check')] self.start_end_XY_Radio=[sg.Radio(text='grab area',group_id='grab_check',enable_events=False,key='grab_check')] self.start_end_Y=[sg.Text('start x'),sg.In(size=(5,1),enable_events=True,key='mouse_x_start'),sg.Text('end x'),sg.In(size=(5,1),enable_events=True,key='mouse_x_end')] self.start_end_X=[sg.Text('start y'),sg.In(size=(5,1),enable_events=True,key='mouse_y_start'),sg.Text('end y'),sg.In(size=(5,1),enable_events=True,key='mouse_y_end')] self.separator=[sg.HorizontalSeparator()] self.image_window = [sg.Image(filename="data\MatejkoKonst3Maj1791.png",background_color='white',enable_events=True,size=(300,300),key='_image_')] self.column_1=[ self.start_end_XY_Radio, self.start_end_Y, self.start_end_X, self.separator, [sg.Text('in text'), sg.In(size=(25, 1),enable_events=False,key='in')], [sg.Button('grab',key='_grab_'),sg.Button('calc',key='_calc_'),sg.Button('remove',key='_remove_') ], [sg.Listbox(values=self.list,enable_events=True,size=(30,10), key='_list_',auto_size_text=True)] ] # self.column_3 = [ # , # [sg.Text('out text '), sg.In(size=(25, 1),enable_events=True,key='out')], # [sg.Text('extra '), sg.In(size=(25, 1),enable_events=True,key='extra')], # ] self.column_2 = [ self.image_window ] self.layout = [ [sg.Column(self.column_1),sg.Column(self.column_2,key='column_2')] ] self.window = sg.Window('BlackJack',self.layout,resizable=True) self.keyboard_listener=KeyboardListener(on_press=self.on_press, on_release=self.on_release) self.mouse_listener = MouseListener(on_move=self.on_move, on_click=self.on_click,onscroll=self.on_scroll) self.mouse = Controller() self.mouse_button = Button self.keyboard = Controller()
def __init__(self, file_manager): self.file = '' self.fileManager = file_manager self.log = Logger('Recorder') self.mouseListener = MouseListener(on_click=self.onClick, on_scroll=self.onScroll, on_move=self.onMove) self.keyboardListener = KeyboardListener(on_press=self.onPress, on_release=self.onRelease) self.clock = Clock() self.alert = Alert('RPTool - Recording') self.drag_start = (0, 0) self.drag_end = (0, 0) self.verifier = Verifier() self.pauseTrace = False
def __init__(self, file_manager): self.fileManager = file_manager self.log = Logger('PlayBack') self.traces = [] self.hostKeys = [] self.keyboardListener = KeyboardListener(on_press=self.onPress, on_release=self.onRelease) self.stopped = False self.interval = 0 self.file = '' self.alert = Alert('RPTool - Playback') self.setting = Settings('rptool.cfg') self.verifier = Verifier()
def start_record(self): self.log = open(self.replay_file, "w") self.init_time = time.time() * 1000 # To make microseconds keyboard_listener = KeyboardListener(on_press=self.__on_press, on_release=self.__on_release) mouse_listener = MouseListener(on_click=self.__on_click, on_scroll=self.__on_scroll) keyboard_listener.start() mouse_listener.start() keyboard_listener.join() mouse_listener.stop() keyboard_listener.stop() self.log.flush() self.log.close()
def stop(self): # keyboard listener functions def on_release(key): print(key) if key == Key.esc: # if key esc is pressed stop global main_client self.control = False if main_client.stop_connection("client"): self.close("first") else: self.control = True # create listener with KeyboardListener(on_release=on_release) as keyboard_listener: # start listener keyboard_listener.join()
def __init__(self, game_object): self.game_object = game_object self.events_list_array = [] self.start_time = time.time() self.interval = 0.1 self.mouse_count = 0 self.mouse = Controller() self.keyboard_listener = KeyboardListener(on_press=self.on_press, on_release=self.on_release) self.mouse_listener = MouseListener(on_move=self.on_move, on_click=self.on_click, on_scroll=self.on_scroll) self.keyboard_listener.start() self.mouse_listener.start() self.listener_on(True)
def main(): roiCoords = pickROI() global stopThreads while True: stopThreads = False # Flag to stop all running threads response = input( '\nNow please start the game, then return to this terminal \n' 'and press enter as soon as the first enemy appears [q to quit anytime]' ) if response == 'q': break print('\nSit back and hold my beer \n\nSearching and destroying...') print('(Press "q" to quit anytime)') kListenerThread = KeyboardListener(on_press=on_press, on_release=on_release) kListenerThread.start() searchAndDestroyThread = Thread(target=searchAndDestroy, args=(lambda: stopThreads, roiCoords), kwargs={ 'timeOut': 180, 'verbose': False }) searchAndDestroyThread.start() # Blocking main Thread until searchAndDestroyThread thread finish searchAndDestroyThread.join() kListenerThread.stop( ) # killing in case searchAndDestroyThread is killed from inside (timeout) response = input( '\nPlay another game (same ROI)? [press enter to continue or q to quit]: ' ) if response == 'q': break # End reached, closing all openCV open windows if any cv2.destroyAllWindows()
def get_color_spots() -> Optional[Dict[Color, Location]]: colors = dict() hard_coded_colors = [((105, 221, 0), "green"), ((255, 204, 0), "yellow"), ((255, 126, 0), "orange"), ((255, 61, 61), "red"), ((192, 0, 255), "purple"), ((255, 62, 212), "magenta"), ((0, 120, 255), "blue"), ((0, 222, 255), "cyan"), ((255, 255, 255), "white"), ((42, 42, 42), "black")] print(color_header("Calibrate Color Picker")) def on_click(x, y, button, pressed): if pressed and button == Button.left: colors[hard_coded_colors[len(colors)][0]] = (x, y) index = len(colors) if index >= len(hard_coded_colors): print("Now you're all done!") return False elif index == 3: color = hard_coded_colors[index] print( f"Yes, for every color now... And then the {color[1]} dot." ) else: color = hard_coded_colors[index] print(f"And then the {color[1]} dot.") print(f"First, click the {hard_coded_colors[0][1]} dot.") with MouseListener(on_click=on_click) as listener: def detect(key): if key == Key.esc: listener.stop() return False with KeyboardListener(on_press=detect): listener.join() if len(colors) == len(hard_coded_colors): return colors else: return None
def get_region() -> Optional[Region]: locations: List[Location] = [] print(color_header("Calibration Region")) print("Please set the editor region by clicking on any 3 of the 4 farthest " \ "sides on the cell editor. One for the top, left, etc... The order, " \ "neither the sides matter, as long as you click on a side you haven't " \ "clicked before.") print("Press ESC at any time to cancel.") def on_click(x, y, button, pressed): if pressed and button == Button.left: locations.append((x, y)) if len(locations) >= 3: return False else: print(f'{3 - len(locations)} more click' \ f'{"s" if 3 - len(locations) != 1 else ""}...') with MouseListener(on_click=on_click) as listener: def detect(key): if key == Key.esc: listener.stop() return False with KeyboardListener(on_press=detect): listener.join() if len(locations) != 3: print("Calibration canceled.") return None print("Calibration finished.") offset_x = min([x for (x, _) in locations]) offset_y = min([y for (_, y) in locations]) diamater = max([ max([x for (x, _) in locations]) - offset_x, max([y for (_, y) in locations]) - offset_y ]) return (offset_x, offset_y, diamater)
def run(self): with MouseListener(on_click=self.on_click, on_scroll=self.on_scroll) as mouse_listener: def on_keyboard_press(key): if key == keyboard.Key.esc: mouse_listener.stop() FileSaver.save_to_file(self.filename, self.sequence_name, self.sequence_id, self.events) return False elif key == keyboard.Key.caps_lock: self.on_caps_lock_record_move( *self.mouse_controller.position) with KeyboardListener( on_press=on_keyboard_press) as keyboard_listener: keyboard_listener.join() mouse_listener.join()
def attach_listener(): # Detects key presses print("Key listener attached") with KeyboardListener(on_press=on_keyboard_press) as listener: listener.join()