def swipe(self, p1, p2, duration=0.5, steps=5, fingers=1, button='left'): if button is "middle": button = Button.middle elif button is "right": button = Button.right elif button is "left": button = Button.left else: raise ValueError("Unknow button: " + button) x1, y1 = p1 x2, y2 = p2 x1 = x1 + self.monitor["left"] x2 = x2 + self.monitor["left"] y1 = y1 + self.monitor["top"] y2 = y2 + self.monitor["top"] ratio_x = self.monitor["width"] / self.singlemonitor["width"] ratio_y = self.monitor["height"] / self.singlemonitor["height"] x2 = x1 + (x2 - x1) / ratio_x y2 = y1 + (y2 - y1) / ratio_y m = Controller() interval = float(duration) / (steps + 1) m.position = (x1, y1) m.press(button) time.sleep(interval) for i in range(1, steps + 1): m.move( int((x2 - x1) / steps), int((y2 - y1) / steps) ) time.sleep(interval) m.position = (x2, y2) time.sleep(interval) m.release(button)
def mouse_click_on_point(x_position, y_position): """moves the mouse corsair to the wanted position and clicking on it :param x_position: x position :param y_position: y position :return: """ mouse = Controller() # Read pointer position print('The current pointer position is {0}'.format(mouse.position)) # Set pointer position mouse.position = (x_position, y_position) print('Now we have moved it to {0}'.format(mouse.position)) # Move pointer relative to current position mouse.move(5, -5) # Press and release mouse.press(Button.left) mouse.release(Button.left) # Double click; this is different from pressing and releasing # twice on Mac OSX mouse.click(Button.left, 2) # Scroll two steps down mouse.scroll(0, 2)
def DoMove(self): mouse = Controller() while 1: mouse.move(2, 0) time.sleep(5) mouse.move(-2, 0) time.sleep(10)
def mouseMove(): hor = 0.1 ver = 0.1 mouse = Controller() while(True): time.sleep(60) mouse.move(hor, ver)
def main(): mouse = Controller() random.seed() # mouse.position = (random.randint(0, 2559), random.randint(0, 1439)) # print("Current Mouse Position is {0}".format(mouse.position)) mouse.move(5, -5) time.sleep(3)
def main(): mouse = Controller() # Read pointer position print("The current pointer position is {0}".format(mouse.position)) print("Now please stare at your mouse, not the terminal :)") print("The mouse will move to the center of the screen\n") time.sleep(MOUSE_SLEEP_INTERVAL) # Set pointer position mouse.position = (1400, 900) print("Now we have moved it to {0}".format(mouse.position)) print("A move based on absolute position") print("Then the mouse will move to the right\n") time.sleep(MOUSE_SLEEP_INTERVAL) # Move pointer relative to current position mouse.move(50, 0) print("Now we have moved it to {0}".format(mouse.position)) print("A move based on relative position") print("Then we will click the right mouse button\n") time.sleep(MOUSE_SLEEP_INTERVAL) # Press and release mouse.press(Button.right) mouse.release(Button.right) print( "Then we will move to the left and double click the left mouse button\n" ) time.sleep(MOUSE_SLEEP_INTERVAL) mouse.move(-50, 0) # Double click; this is different from pressing and releasing mouse.click(Button.left, 2)
def main(argv): wait_seconds = 30 distance = 100 random_position = False try: opts, args = getopt.getopt(argv, "hrs:d:", ['seconds=', 'distance=']) except getopt.GetoptError: print_help() for opt, arg in opts: if opt == '-h': print_help() elif opt == '-r': random_position = True elif opt == '-d': try: wait_seconds = int(arg) except ValueError: print_help() elif opt == '-s': try: wait_seconds = int(arg) except ValueError: print_help() mouse = Controller() monitor = get_monitors()[0] while (True): time.sleep(wait_seconds) if not random_position: mouse.move(randint(-distance, distance), randint(-distance, distance)) else: mouse.position = (randint(0, monitor.width), randint(0, monitor.height))
class MouseThread(QThread): def __init__(self): QThread.__init__(self) self.controller = Controller() self.moving_x = 0 self.moving_y = 25 self.mxHeight=GetSystemMetrics(1) self.mxWidth=GetSystemMetrics(0) change_value = pyqtSignal(str) def run(self): while True: time.sleep(.2) self.controller.move(self.moving_x,self.moving_y) pos=self.controller.position if self.moving_y: if self.moving_y>0: if pos[1]>=self.mxHeight-1: self.moving_y=-self.moving_y else: if pos[1]<=0: self.moving_y=-self.moving_y else : if self.moving_x > 0: if pos[0] >= self.mxWidth-1: self.moving_x = -self.moving_x else: if pos[0] <= 0: self.moving_x = -self.moving_x self.change_value.emit("")
def connect_to_corresponding_wire(self): # This wire's position as a tuple my_pos = tuple(self.__pos) # The other wire's position as a tuple other_pos = tuple(self.__corresponding_wire.get_pos()) print(f"{my_pos} is connecting to {other_pos}.") # Object used to control mouse movements and actions mouse = Controller() # Initial position is this wire's position mouse.position = my_pos # Left button is pressed mouse.press(Button.left) print("> button pressed") # Wait a bit so the movement is correctly considered time.sleep(0.032) # Move to mouse to the other wire's position while pressing the left button mouse.move(other_pos[0] - my_pos[0], other_pos[1] - my_pos[1]) print("> mouse moved") # Wait a bit so the movement is correctly considered time.sleep(0.032) # Release the left button mouse.release(Button.left) print("> button released") # Wait a bit so the movement is correctly considered time.sleep(0.032)
def read_tablet(rm_inputs, *, orientation, monitor_num, region, threshold, mode): """Loop forever and map evdev events to mouse Args: rm_inputs (dictionary of paramiko.ChannelFile): dict of pen, button and touch input streams orientation (str): tablet orientation monitor_num (int): monitor number to map to region (boolean): whether to selection mapping region with region tool threshold (int): pressure threshold mode (str): mapping mode """ from pynput.mouse import Button, Controller mouse = Controller() monitor = get_monitor(region, monitor_num, orientation) log.debug('Chose monitor: {}'.format(monitor)) x = y = 0 while True: _, _, e_type, e_code, e_value = struct.unpack( '2IHHi', rm_inputs['pen'].read(16)) e_bit = libevdev.evbit(e_type, e_code) e = libevdev.InputEvent(e_bit, value=e_value) if e.matches(EV_ABS): # handle x direction if e.matches(EV_ABS.ABS_Y): log.debug(e.value) x = e.value # handle y direction if e.matches(EV_ABS.ABS_X): log.debug('\t{}'.format(e.value)) y = e.value # handle draw if e.matches(EV_KEY.BTN_TOUCH): log.debug('\t\t{}'.format(e.value)) if e.value == 1: log.debug('PRESS') mouse.press(Button.left) else: log.debug('RELEASE') mouse.release(Button.left) if e.matches(EV_SYN): mapped_x, mapped_y = remap(x, y, wacom_width, wacom_height, monitor.width, monitor.height, mode, orientation) mouse.move(monitor.x + mapped_x - mouse.position[0], monitor.y + mapped_y - mouse.position[1])
class Finger(): def __init__(self, speed=10): self._mse = MouseControl() self._kbd = KbdControl() self._speed = speed def type(self, keys): self._kbd.type(keys) def move(self, dx, dy, type_='abs'): if type_ == 'abs': self._mse.position = (dx, dy) else: self._mse.move(dx, dy) def click(self, button='left', count=1): button = getattr(Button, button, 'left') self._mse.click(button, count) def scroll(self, vscr=2, hscr=0): self._mse.scroll(hscr, vscr) def drag(self, to=(), frm=(), button='left'): # simulate a drag. TODO: make in increments instead of instant if not frm: frm = self._mse.position if not to: to = self._mse.position button = getattr(Button, button, 'left') self._mse.press(button) self._mse.position = to self._mse.release(button) #while not self._mse.position == to: # simulate movement one step at a time #x_pos = self._mse.position[0] #y_pos = self._mse.position[1] #if not x_pos == to[0]: x_pos def press(self, device='mouse', button='left'): if device == 'mouse': self._mse.press(getattr(Button, button, 'left')) else: key = button if len(button) == 1 else getattr(Key, button, 'space') self._kbd.press(key) def release(self, device='mouse', button='left'): # specify mouse or keyboard if device == 'mouse': self._mse.release(getattr(Button, button, 'left')) else: key = button if len(button) == 1 else getattr(Key, button, 'space') self._kbd.release(key)
def controlMouse(): mouse = Controller() keyboard = Listener() print("Press Enter to exit") while True: mouse.move(random.randint(0, 10), random.randint(0, 10)) with Listener(on_press=on_press) as listener: if not validity: raise SystemExit time.sleep(1)
def movement( self ): #function for movements of mouse so that its cant detect its a bot mouse = Controller() mouse.position = (10, 20) mouse.move(60, -150) mouse.move(20, -17) mouse.move(30, -40) mouse.scroll(0, 2) mouse.scroll(0, -100) mouse.scroll(0, -120)
def mouse_mover(): mouse = Controller() keep_moving_mouse = True l = True while keep_moving_mouse: time.sleep(.01) if l: mouse.move(0, -1) else: mouse.move(0, 1) l = not l
def read_tablet(args, remote_device): """Loop forever and map evdev events to mouse""" from screeninfo import get_monitors from pynput.mouse import Button, Controller lifted = True new_x = new_y = False mouse = Controller() monitor = get_monitors()[args.monitor] log.debug('Chose monitor: {}'.format(monitor)) while True: _, _, e_type, e_code, e_value = struct.unpack('2IHHi', remote_device.read(16)) if e_type == e_type_abs: # handle x direction if e_code == e_code_stylus_xpos: log.debug(e_value) x = e_value new_x = True # handle y direction if e_code == e_code_stylus_ypos: log.debug('\t{}'.format(e_value)) y = e_value new_y = True # handle draw if e_code == e_code_stylus_pressure: log.debug('\t\t{}'.format(e_value)) if e_value > args.threshold: if lifted: log.debug('PRESS') lifted = False mouse.press(Button.left) else: if not lifted: log.debug('RELEASE') lifted = True mouse.release(Button.left) # only move when x and y are updated for smoother mouse if new_x and new_y: mapped_x, mapped_y = remap(x, y, stylus_width, stylus_height, monitor, args.orientation, args.mode) mouse.move(monitor.x + mapped_x - mouse.position[0], monitor.y + mapped_y - mouse.position[1]) new_x = new_y = False
def keystroke_action(inject): keyboard = KeyboardController() mouse = MouseController() for command in inject: command = command.split(' ') c_type, c_data = command[0], command[1] if c_type == 'press': try: c_data = eval(f'Key.{c_data}') except: pass finally: keyboard.press(c_data) keyboard.release(c_data) elif c_type == 'hold': try: c_data = eval(f'Key.{c_data}') except: pass finally: keyboard.press(c_data) elif c_type == 'release': try: c_data = eval(f'Key.{c_data}') except: pass finally: keyboard.release(c_data) elif c_type == 'type': keyboard.type(' '.join(command[1:])) elif c_type == 'position': mouse.position = [int(position) for position in c_data.split(',')] elif c_type == 'move': move_positions = [int(position) for position in c_data.split(',')] mouse.move(move_positions[0], move_positions[1]) elif c_type == 'mhold': mouse.press(eval(f'Button.{c_data}')) elif c_type == 'mrelease': mouse.release(eval(f'Button.{c_data}')) elif c_type == 'click': mouse.press(eval(f'Button.{c_data}')) mouse.release(eval(f'Button.{c_data}')) elif c_type == 'dclick': mouse.click(eval(f'Button.{c_data}'), 2) elif c_type == 'scroll': scroll_positions = [int(position) for position in c_data.split(',')] mouse.scroll(scroll_positions[0], scroll_positions[1]) elif c_type == 'sleep': time.sleep(float(c_data)) else: raise Exception('Invalid keystroke command')
def move_mouse(): """ :return: None, moves the mouse relative to current position """ mouse = MouseController() # choose random x and y position to move mouse to x = randint(-30, 30) y = randint(-30, 30) mouse.move(x, y) logging.info(f'Moved mouse relative to current position {x, y}')
def test_itemscanvas_menu(self): canvas = ItemsCanvas() canvas.pack() self.window.wm_geometry("+0+0") self.window.update() mouse_controller = Controller() mouse_controller.position = (0, 0) mouse_controller.move(30, 40) self.window.update() mouse_controller.press(Button.right) self.window.update() mouse_controller.release(Button.right) self.window.update()
def mouse_(word='a'): while 1: if word == 'a': word = speech_recognizer() mouse = Controller() if 'down' in word: mouse.move(0, 40) elif 'up' in word or 'upper side' in word: mouse.move(0, -40) elif 'right' in word: mouse.move(40, 0) elif 'left' in word: mouse.move(-40, 0) elif 'on first link' in word: mouse.position = (250, 300) elif 'first link' in word: mouse.position = (250, 300) mouse.press(Button.left) mouse.release(Button.left) elif 'at middle' in word: mouse.position(670, 400) if 'left click' in word or 'click left' in word: mouse.press(Button.left) mouse.release(Button.left) if 'right click' in word or 'click right' in word: mouse.press(Button.right) mouse.release(Button.right) elif 'stop song' in word or 'play' in word or 'paly song' in word: mouse.position = (400, 300) mouse.press(Button.left) mouse.release(Button.left) else: return word word = 'a'
def mouse_drag(initial_x_pos, initial_y_pos, final_x_pos, final_y_pos): """Dragging an object from initial position to its final position :param initial_x_pos: Initial x position :param initial_y_pos: Initial y position :param final_x_pos: Final x position :param final_y_pos: Final y position """ mouse = Controller() mouse.position = (initial_x_pos, initial_y_pos) mouse.press(Button.left) mouse.move(final_x_pos - initial_x_pos, final_y_pos - initial_y_pos) time.sleep(1) mouse.release(Button.left)
class Mouse(): def __init__(self): self.mouse = Controller() self.x = self.mouse.position[0] self.y = self.mouse.position[1] self.pos = (self.x, self.y) def update(self): ''' Update the mouses current position. ''' self.x = self.mouse.position[0] self.y = self.mouse.position[1] self.pos = (self.x, self.y) def move_to(self, pos): ''' Move the mouse to x2,y2 Using calculation to get the relative coords between (x1,y1) and (x2,y2). ''' self.update() x1 = self.x y1 = self.y xr = pos[0] - x1 yr = pos[1] - y1 self.mouse.move(xr, yr) def left_single_click(self): ''' Perform a single left click with the mouse. ''' self.mouse.click(Button.left, 1) def left_double_click(self): ''' Perform a double click with the left mouse button. ''' self.mouse.click(Button.left, 2) def get_pos(self): ''' Get the current position of the mouse. ''' self.update() return self.pos
def test_itemscanvas_drag(self): canvas = ItemsCanvas(self.window) canvas.pack() canvas.add_item("item", font=("default", 16)) self.window.wm_geometry("+0+0") self.window.update() mouse_controller = Controller() mouse_controller.position = (30, 40) self.window.update() mouse_controller.press(Button.left) self.window.update() mouse_controller.move(100, 100) self.window.update() mouse_controller.release(Button.left) self.window.update()
def main(): mouse = Mouse() mouse.move(450, 450) mouse.press(Button.left) mouse.release(Button.left) time.sleep(2) keyboard = Keyboard() keyboard.type('sunny') keyboard.press(Key.space) keyboard.release(Key.space) keyboard.press(Key.enter) keyboard.release(Key.enter)
def swipe(self, p1, p2, duration=0.5, steps=5, fingers=1, button='left'): set_foreground_window(self.window) if button is "middle": button = Button.middle elif button is "right": button = Button.right elif button is "left": button = Button.left else: raise ValueError("Unknow button: " + button) x1, y1 = p1 x2, y2 = p2 # 设置坐标时相对于整个屏幕的坐标: x1 = x1 + self.monitor["left"] x2 = x2 + self.monitor["left"] y1 = y1 + self.monitor["top"] y2 = y2 + self.monitor["top"] # 双屏时,涉及到了移动的比例换算: if len(self.screen.monitors) > 2: ratio_x = ( self.monitor["width"] + self.monitor["left"]) / self.singlemonitor["width"] ratio_y = ( self.monitor["height"] + self.monitor["top"]) / self.singlemonitor["height"] x2 = int(x1 + (x2 - x1) * ratio_x) y2 = int(y1 + (y2 - y1) * ratio_y) p1 = (x1, y1) p2 = (x2, y2) from_x, from_y = get_action_pos(self.window, p1) to_x, to_y = get_action_pos(self.window, p2) m = Controller() interval = float(duration) / (steps + 1) m.position = (from_x, from_y) m.press(button) time.sleep(interval) for i in range(1, steps + 1): m.move( int((to_x - from_x) / steps), int((to_y - from_y) / steps) ) time.sleep(interval) m.position = (x2, y2) time.sleep(interval) m.release(button)
def mimic_mouse(): import serial serialport = serial.Serial("/dev/serial0", 115200, timeout=1) def get_v(x, y, v=3): dx = 0 dy = 0 if x > 700: dy = v if x < 300: dy = -v if y > 700: dx = -v if y < 300: dx = +v return (dx, dy) def parse_info(str): #print(str) try: info = str.split(" ") x = eval(info[0].split("'")[1].split(',')[0]) y = eval(info[1].split(",")[0]) button = eval(info[2][0]) return (x, y, button) except: return None mouse = Controller() while True: info = parse_info(str(serialport.readline())) if info != None: c_p = (info[0], info[1]) button = info[2] if button == 1: mouse.press(Button.left) else: mouse.release(Button.left) v = get_v(c_p[0], c_p[1]) dx = v[0] dy = v[1] mouse.move(dx, dy) else: pass
def shoot(): mouse = Controller() mouse.press(Button.right) time.sleep(0.1) mouse.release(Button.right) time.sleep(1) mouse.press(Button.left) time.sleep(0.1) mouse.release(Button.left) mouse.move(1, 0) time.sleep(1) mouse.press(Button.right) time.sleep(0.1) mouse.release(Button.right) time.sleep(1) mouse.press(Button.left) time.sleep(0.1) mouse.release(Button.left)
class MouseController(): def __init__(self): pass self.mouse = Controller() def mouse_position(self): # Read pointer position print('The current pointer position is {0}'.format( self.mouse.position)) return self.mouse.position def mouse_postiion_set(self, x, y): # Set pointer position self.mouse.position = (x, y) print('Now we have moved it to {0}'.format(self.mouse.position)) def mouse_move(self, x, y): # Move pointer relative to current position self.mouse.move(x, y) def mouse_press(self, right=False): if right == True: self.mouse.press(Button.right) else: self.mouse.press(Button.left) def mouse_release(self, right=False): if right == True: self.mouse.release(Button.right) else: self.mouse.release(Button.left) def mouse_double_click(self, right=False): # Double click; this is different from pressing and releasing # twice on Mac OSX if right == 'right' or right == True: self.mouse.click(Button.right, 2) else: self.mouse.click(Button.right, 2) def mouse_scroll(self, x, y): # Scroll two steps down self.mouse.scroll(x, y)
class Main(): def __init__(self): self.mouse = Controller() while True: with open("/dev/input/js0", "rb") as self.controller: self.controller.read(168) self.input = self.controller.read(8).hex() if self.input[-4:-2] == "01": if self.input[-8:-6] == "01": if self.input[-4:] == "0101": self.mouse.press(Button.left) if self.input[-4:] == "0100": self.mouse.press(Button.right) if self.input[-8:-6] == "00": if self.input[-4:] == "0101": self.mouse.release(Button.left) if self.input[-4:] == "0100": self.mouse.release(Button.right) if self.input[-4:-2] == "02": if self.input[-2:] == "00": if int(self.input[-6:-4], 16) > 127: self.movement = int(self.input[-6:-4], 16) - 255 else: self.movement = int(self.input[-6:-4], 16) self.mouse.move(self.movement / 2, 0) if self.input[-2:] == "01": if int(self.input[-6:-4], 16) > 127: self.movement = int(self.input[-6:-4], 16) - 255 else: self.movement = int(self.input[-6:-4], 16) self.mouse.move(0, self.movement / 2) if self.input[-2:] == "02": if int(self.input[-6:-4], 16) > 127: self.movement = int(self.input[-6:-4], 16) - 255 else: self.movement = int(self.input[-6:-4], 16) self.mouse.scroll(-self.movement / 2, 0) if self.input[-2:] == "03": if int(self.input[-6:-4], 16) > 127: self.movement = int(self.input[-6:-4], 16) - 255 else: self.movement = int(self.input[-6:-4], 16) self.mouse.scroll(0, -self.movement / 2)
def _mouse_press_release(where=None, action=None, button=None, in_region=None): """Mouse press/release. :param where: Location , image name or Pattern. :param action: 'press' or 'release'. :param button: 'left','right' or 'middle'. :param in_region: Region object in order to minimize the area. :return: None. """ if isinstance(where, Pattern): needle = cv2.imread(where.get_file_path()) height, width, channels = needle.shape p_top = positive_image_search(pattern=where, region=in_region) if p_top is None: raise FindError('Unable to click on: %s' % where.get_file_path()) possible_offset = where.get_target_offset() if possible_offset is not None: location = Location(p_top.x + possible_offset.x, p_top.y + possible_offset.y) pyautogui.moveTo(location.x, location.y) if action == 'press': pyautogui.mouseDown(location.x, location.y, button) elif action == 'release': pyautogui.mouseUp(location.x, location.y, button) else: location = Location(p_top.x + width / 2, p_top.y + height / 2) pyautogui.moveTo(location.x, location.y) if action == 'press': pyautogui.mouseDown(location.x, location.y, button) elif action == 'release': pyautogui.mouseUp(location.x, location.y, button) elif isinstance(where, str): mouse = Controller() ocr_search = OCRSearch() a_match = ocr_search.text_search_by(where, True, in_region) if a_match is not None: location = Location(a_match['x'] + a_match['width'] / 2, a_match['y'] + a_match['height'] / 2) mouse.move(location.x, location.y) if action == 'press': mouse.press(button) elif mouse == 'release': mouse.release(button)
def aim(): global cap global target global stop mouse = Controller() while True: if stop: break cur = target.current.get() if cur == (0, 0): continue pre = target.prev.get() # rheadpos = (int(cur[0]+(cur[0]-pre[0]) - cap.width/2)+31, int(cur[1]+(cur[1]-pre[1]) - cap.height/2)+15) rheadpos = (int(cur[0] - cap.width / 2) + 31, int(cur[1] - cap.height / 2) + 20) logger.debug("moving mouse to " + str(rheadpos)) mouse.move(rheadpos[0] * 1.6, rheadpos[1] * 1.3) target.current.set((0, 0)) target.prev.set((0, 0)) time.sleep(0.05)
class MouseKeyboard: def __init__(self): self.keyboard = KeyboardController() self.mouse = MouseController() self.controlKeys = {37:self.keyLeft, 38:self.keyUp, 39:self.keyRight, 40:self.keyDown, 60:self.leftClick, 62:self.rightClick, 8:self.keyBksp, 13:self.keyEnter} def handleButtonPress(self, key): key = key.strip("'\\") try: keyNum = int(key) except ValueError: keyNum = ord(key) try: print('Got {}.'.format(keyNum)) except OSError: pass if keyNum in self.controlKeys.keys(): self.controlKeys[keyNum]() else: try: self.keyboard.press(key) self.keyboard.release(key) except ValueError: print("Failed to press {}: ValueError.".format(key)) def handleMouseMove(self, key): key = key.strip("'\\") (xStr, yStr) = key.split() try: xVal = int(xStr) yVal = int(yStr) except ValueError: print("Got MouseMove but x, y string format unexpected: '{}', '{}'".format(xStr, yStr)) print("Mouse Moving by: {}, {}".format(xVal,yVal)) self.mouse.move(xVal*8,yVal*8) def keyUp(self): self.keyboard.press(Key.up) self.keyboard.release(Key.up) def keyLeft(self): self.keyboard.press(Key.left) self.keyboard.release(Key.left) def keyRight(self): self.keyboard.press(Key.right) self.keyboard.release(Key.right) def keyDown(self): self.keyboard.press(Key.down) self.keyboard.release(Key.down) def keyBksp(self): self.keyboard.press(Key.backspace) self.keyboard.release(Key.backspace) def keySpace(self): self.keyboard.press(Key.space) self.keyboard.release(Key.space) def keyEnter(self): self.keyboard.press(Key.enter) self.keyboard.release(Key.enter) def leftClick(self): self.mouse.click(Button.left) def rightClick(self): self.mouse.click(Button.right)