Example #1
0
def get_pixel(x=-1, y=-1):
    """
    Returns RGB of given x and y location.
    If no arguments given then default location will be current mouse position
    :param x: x coordinate of pixel to obtain
    :param y: y coordinate of pixel to obtain
    """

    from win32gui import GetDesktopWindow, GetWindowDC, GetPixel
    from win32api import GetCursorPos

    if x == -1 and y == -1:
        x = GetCursorPos()[0]
        y = GetCursorPos()[1]

    rgb = ()
    if x != -1 and y != -1:
        i_desktop_window_id = GetDesktopWindow()
        i_desktop_window_dc = GetWindowDC(
            i_desktop_window_id)  # device context
        long_colour = GetPixel(i_desktop_window_dc, x, y)
        i_colour = int(long_colour)
        rgb = (i_colour & 0xff), ((i_colour >> 8) & 0xff), (
            (i_colour >> 16) & 0xff)  # magical bit-shifting

    elif x == -1:
        raise ValueError("Missing 'x' coordinate")
    elif y == -1:
        raise ValueError("Missing 'y' coordinate")

    return rgb
Example #2
0
    def log(self, event, content=None):
        uid = str(uuid4())

        with mss() as sht:
            fn = "recordings/{}/screenshots/{}.png".format(self.name, uid)
            sht.shot(mon=-1, output=fn)

        data = {
            "uid":
            uid,
            "machine_id":
            self.machine_id,
            "timestamp":
            time(),
            "mouse_x":
            GetCursorPos()[0],
            "mouse_y":
            GetCursorPos()[1],
            "screen_res_x":
            GetSystemMetrics(0),
            "screen_res_y":
            GetSystemMetrics(1),
            "foreground_app_process":
            self.get_current_foreground_app_process_name(),
            "foreground_app_title":
            self.get_current_foreground_app_title(),
            "event":
            event,
        }

        if content:
            data["content"] = content

        with open("recordings/{}/actions.json".format(self.name), "a") as f:
            f.write(json.dumps(data) + "\n")
Example #3
0
    def mouseMoveEvent(self, event):
        x, y = GetCursorPos()

        self.label.setText(str(GetCursorPos()))
        RGB = self.get_pixel_colour(x, y)
        HSV = colorsys.rgb_to_hsv(RGB[0], RGB[1], RGB[2])

        def rgb_to_hex(rgb):
            return '%02x%02x%02x' % (rgb[0], rgb[1], rgb[2])

        self.color = '{:02x}{:02x}{:02x}'.format(RGB[0], RGB[1], RGB[2])
        print(self.color)
        self.label1.setStyleSheet(
            "QLabel {background-color:rgb(%s , %s , %s)}" % RGB)

        self.label_RGB.setText(f"""
        Coordinates:
        ({x},{y})

        RGB COLOURS:
        RED: {RGB[0]}
        BLUE: {RGB[1]} 
        GREEN: {RGB[2]}
                               
        HSV COLOURS:
        HUE:{HSV[0]}
        SAT:{HSV[1]}
        VAL:{HSV[2]}
                               """)
Example #4
0
 def _cal_pixel_speed(self):
     if self.frames >= 99:
         self.pposx = self.posx
         self.pposy = self.posy
     self.posx = GetCursorPos()[0]
     self.posy = GetCursorPos()[1]
     if self.frames >= 100:
         self.pixel_speed = hypot(self.posx-self.pposx, self.posy-self.pposy)/(self.hun_time/100)
     return self.pixel_speed
Example #5
0
    def click(button1, button2):
        # example: HumanMouse.click('Right', 'Left')
        # button1 - generally used mouse button
        # button2 - missclick mouse button

        sleep(93 / randint(83, 201))
        fromPoint = GetCursorPos()

        if randint(1, 19) != 1:
            HumanMouse.buttonPressedReleased(button1)

        else:
            temp_rand = randint(0, 1)

            if temp_rand == 0:
                # double click
                HumanMouse.buttonPressedReleased(button1)
                sleep(randint(43, 113) / 1000)
                HumanMouse.buttonPressedReleased(button1)

            elif temp_rand == 1:
                # missclick
                HumanMouse.buttonPressedReleased(button2)
                sleep(randint(43, 113) / 1000)
                HumanMouse.buttonPressedReleased(button1)
def get_cursor_pos():
    try:
        pos = GetCursorPos()
    except:
        log_record('не удалось получить позицию курсора')
        pos = None
    return pos
Example #7
0
    def record_single_coord(self, event):
        '''Function for recording a single coordinate'''
        num_id = self.first_coord.GetId()
        x = wx.FindWindowById(num_id + 1)
        y = wx.FindWindowById(num_id + 2)

        cursorpos = GetCursorPos()

        def stop_record():
            '''Sub-function for resetting label color and stopping recording'''
            self.first_coord.SetForegroundColour("black")
            self.first_coord.Refresh()
            self.stop_record()

        if self.movement_relative.GetValue():
            # Set origin point for relative coordinates
            if not self.last_coord:
                self.last_coord = cursorpos
            else:
                # Input coordinates in list (relative to origin point)
                for i, widget in enumerate([x, y]):
                    widget.SetValue(cursorpos[i] - self.last_coord[i])
                stop_record()
        else:
            # Input cursor position in list (absolute coordinates)
            for i, widget in enumerate([x, y]):
                widget.SetValue(cursorpos[i])
            stop_record()

        return True
Example #8
0
def mmove(fin_pos):
    init_pos = GetCursorPos()

    bez1 = mouse_bez(init_pos, fin_pos, 30, 1000)
    # bez1 = [[round(v) for v in x] if type(x) is not str else x for x in bez1]

    for point in bez1:
        # SetCursorPos((point[0], point[1]))
        SetCursorPos((int(point[0]), int(point[1])))
Example #9
0
 def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
     self.absolute_mouse_pos = GetCursorPos()
     self.game_window_position = GetWindowRect(self.game_window_handler)
     SetWindowPos(
         self.game_window_handler, HWND_TOP,
         self.absolute_mouse_pos[0] - self.app_window_move_offset[0],
         self.absolute_mouse_pos[1] - self.app_window_move_offset[1],
         self.game_window_position[2] - self.game_window_position[0],
         self.game_window_position[3] - self.game_window_position[1],
         SWP_NOREDRAW)
Example #10
0
    def move(toPoint, duration=2, humanCurve=None):
        # moving your mouse in the bezier curve path

        fromPoint = GetCursorPos()

        if not humanCurve:
            humanCurve = HumanCurve(fromPoint, toPoint)

        for point in humanCurve.points:
            sleep(duration / len(humanCurve.points))
            SetCursorPos((int(point[0]), int(point[1])))
Example #11
0
def main(argv=None):
    pargs = parse_args(argv)

    anchor = prev = GetCursorPos()
    delay = pargs.delay

    counter = count(pargs.iterations, -1)
    while next(counter) > 0:
        sleep(delay)
        if GetCursorPos() == prev:  # No user action detected - make a move
            base = anchor if pargs.anchor else prev
            SetCursorPos([i + randint(-5, 5) for i in base])
            if pargs.click:
                mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0)
                sleep(0.2)
                mouse_event(MOUSEEVENTF_LEFTUP, 0, 0)
        else:  # Moved since last check - reset the anchor
            delay = 10
            anchor = GetCursorPos()
        delay = pargs.delay
        prev = GetCursorPos()
Example #12
0
    def buttonPressedReleased(button):

        pos = GetCursorPos()

        if button == 'Right':
            mouse_event(win32con.MOUSEEVENTF_RIGHTDOWN, pos[0], pos[1], 0, 0)
            sleep(randint(43, 113) / 1000)
            mouse_event(win32con.MOUSEEVENTF_RIGHTUP, pos[0], pos[1], 0, 0)

        elif button == 'Left':
            mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, pos[0], pos[1], 0, 0)
            sleep(randint(43, 113) / 1000)
            mouse_event(win32con.MOUSEEVENTF_LEFTUP, pos[0], pos[1], 0, 0)
    def task(self):
        while self.is_running is True:
            sleep(0.1)
            paste = pyperclip.paste()
            if paste != self.prior_paste:
                break

        while True:
            if self.is_running is True:
                sleep(0.1)
                if self.hwnd is not None:
                    paste = pyperclip.paste()
                    if paste != self.prior_paste:
                        if paste not in self.text_display:
                            try:
                                self.translation = self.translator.translate(
                                    paste,
                                    dest=(self.configuration['language map'][
                                        self.configuration['current language']]
                                          ))
                                self.text_display = ''
                                self.text_display += self.translation.text
                                self.text_display += '\n'
                                if len(self.translation.
                                       extra_data['translation'][1]) >= 4:
                                    pron = self.translation.extra_data[
                                        'translation'][1][3]
                                    if pron is not None:
                                        self.text_display += '['
                                        self.text_display += pron
                                        self.text_display += ']'
                                self.write(self.text_display)
                            except:
                                self.write(
                                    'Oops! A network error occured, please try later or change source.'
                                )

                            self.raise_above_all()
                            self.SetForegroundWindow()
                            x, y = GetCursorPos()
                            self.window.geometry('+%d+%d' % (x, y))
                    self.prior_paste = paste
                else:
                    try:
                        self.hwnd = self.get_hwnd(
                            self.configuration['window name'])
                    except:
                        pass

            else:
                return
Example #14
0
    def paintEvent(self, event):

        if keyboard.is_pressed('shift+f') and not self.holding:
            self.holding = True
            self.hold_time = time.time()
        elif not keyboard.is_pressed('shift+f'):
            self.holding = False

        if self.holding and self.hold_time and time.time(
        ) - self.hold_time >= 1 and not self.clicking:
            x, y = GetCursorPos()
            for region in self.active_regions:
                if region[0] <= x <= region[0] + region[2] and region[
                        1] <= y <= region[1] + region[3]:
                    self.setVisible(False)
                    face_img = ImageGrab.grab(self.dimensions)
                    self.setVisible(True)

                    Thread(target=reverse_search.crop_and_upload,
                           args=[face_img, region, self]).start()

        qp = QPainter()
        qp.begin(self)
        qp.setFont(QFont('Decorative', 10))
        qp.setPen(QPen(Qt.green, 5, Qt.SolidLine))

        for region in self.active_regions:
            x, y = GetCursorPos()
            if region[0] <= x <= region[0] + region[2] and region[
                    1] <= y <= region[1] + region[3]:
                qp.setPen(QPen(Qt.red, 5, Qt.SolidLine))
                qp.drawRect(region[0], region[1], region[2], region[3])
                qp.setPen(QPen(Qt.green, 5, Qt.SolidLine))
            else:
                qp.drawRect(region[0], region[1], region[2], region[3])

        qp.end()
Example #15
0
    def _sendRclick(self, hwnd, msg):
        # IPython magic %paste does not work for remote ssh python
        # or Windows Subsystem for Linux, so let's send right click using win32
        def _pasting(hwnd, msg):
            sublime.set_clipboard(msg)
            sleep(0.1)  # important!
            # sending right-click to paste over
            mouse_event(MOUSEEVENTF_RIGHTDOWN | MOUSEEVENTF_ABSOLUTE, 0, 0)
            sleep(0.1)  # important!
            mouse_event(MOUSEEVENTF_RIGHTUP | MOUSEEVENTF_ABSOLUTE, 0, 0)
            # send enter;  int('0x1C0001', 0) works both on WSL and cmd
            PostMessage(hwnd, WM_KEYDOWN, VK_RETURN, int('0x1C0001', 0))
            PostMessage(hwnd, WM_KEYUP, VK_RETURN, int('0xC0000001', 0))

        try:
            # https://stackoverflow.com/a/15503675/566035
            shell = Dispatch("WScript.Shell")
            shell.SendKeys(
                '%'
            )  # Sending Alt key goes around windows security policy change
            SetForegroundWindow(hwnd)
        except:
            self.view.show_popup('Invalid handle ({})'.format(hwnd))
            return

        # move mouse to the center of that window
        oldx, oldy = GetCursorPos()
        x1, y1, x2, y2 = GetWindowRect(hwnd)
        x = int((x1 + x2) / 2)
        y = int((y1 + y2) / 2)
        SetCursorPos((x, y))

        lineN = len(self.view.lines(self.view.sel()[0]))
        # we need to use %cpaste magic to avoid indentation error
        # in case more than 2 lines have indentation.
        if lineN > 2:
            _pasting(hwnd, r"%cpaste")
            _pasting(hwnd, msg)
            _pasting(hwnd, "--")
        else:
            _pasting(hwnd, msg)

        # bring back the mouse cursor
        SetCursorPos((oldx, oldy))

        # bring back the focus to sublime, if subl_handle is known to the plugin
        if subl_handle:
            SetForegroundWindow(subl_handle)
            shell.SendKeys('%')  # cancel the Alt key evoked menu
Example #16
0
def getargument():
    global resolution_w, resolution_h, hwnd, win_rect, win_rect_x, win_rect_y, win_rect_w, win_rect_h
    global center_x, center_y, smart_x, smart_y, wincenter
    global smartsize_defaultw, smartsize_defaulth, smartsize_bigw, smartsize_bigh, smartsize_largew, smartsize_largeh
    global hsmartsize_defaulth, hsmartsize_bigh, hsmartsize_largeh
    global vsmartsize_defaultw, vsmartsize_bigw, vsmartsize_largew
    global taskbar
    resolution_w = GetSystemMetrics(0)
    if taskbar == 1:
        resolution_h = GetSystemMetrics(1) - taskbarsize
    else:
        resolution_h = GetSystemMetrics(1)
    hwnd = win32gui.GetForegroundWindow()
    win_rect = win32gui.GetWindowRect(hwnd)
    win_rect_x = win_rect[0]
    win_rect_y = win_rect[1]
    win_rect_w = win_rect[2] - win_rect_x
    win_rect_h = win_rect[3] - win_rect_y
    center_x = (resolution_w - win_rect_w) / 2
    center_y = (resolution_h - win_rect_h) / 2
    smart_x = [
        resolution_w / 3, resolution_w / 3 * 2, resolution_w,
        resolution_w - win_rect_w
    ]
    smart_y = [
        resolution_h / 3, resolution_h / 3 * 2, resolution_h,
        resolution_h - win_rect_h
    ]
    wincenter = GetCursorPos()
    smartsize_defaultw = resolution_w / smartsize_default[
        0] * smartsize_default[1]
    smartsize_defaulth = resolution_h / smartsize_default[
        0] * smartsize_default[1]
    smartsize_bigw = resolution_w / smartsize_big[0] * smartsize_big[1]
    smartsize_bigh = resolution_h / smartsize_big[0] * smartsize_big[1]
    smartsize_largew = resolution_w / smartsize_large[0] * smartsize_large[1]
    smartsize_largeh = resolution_h / smartsize_large[0] * smartsize_large[1]
    hsmartsize_defaulth = resolution_h / hsmartsize_default[
        0] * hsmartsize_default[1]
    hsmartsize_bigh = resolution_h / hsmartsize_big[0] * hsmartsize_big[1]
    hsmartsize_largeh = resolution_h / hsmartsize_large[0] * hsmartsize_large[1]
    vsmartsize_defaultw = resolution_w / vsmartsize_default[
        0] * vsmartsize_default[1]
    vsmartsize_bigw = resolution_w / vsmartsize_big[0] * vsmartsize_big[1]
    vsmartsize_largew = resolution_w / vsmartsize_large[0] * vsmartsize_large[1]
    def record(self):
        i = 0

        while True:
            if GetCursorPos() == (0, 0):
                break

            new_states = self.get_key_states()

            for state, new_state, virtual_key in zip(
                self.states, new_states, self.virtual_keys
            ):
                if state != new_state:
                    if state < 0:
                        if virtual_key[1] not in self.letters:
                            self.log(virtual_key[1])
                    else:
                        if virtual_key[1] in self.letters:
                            self.letter_sequence += virtual_key[1]
                            typing = True
                        else:
                            typing = False

                        if len(self.letter_sequence) > 2 and not typing:
                            self.log("typing", content=self.letter_sequence)
                            self.letter_sequence = ""
                            typing = False

            if i == 100:
                new_clipboard = self.get_clipboard()

                if self.clipboard != new_clipboard:
                    self.log("clipboard", content=new_clipboard)
                    self.clipboard = new_clipboard

                i = 0

            self.states = new_states

            sleep(0.01)

            i += 1
Example #18
0
def moveMouseTo(x=None, y=None, duration=None):
    current_pixel_coordinates = GetCursorPos()
    start_coords = _to_windows_coordinates(*current_pixel_coordinates)
    end_coords = _to_windows_coordinates(x, y)

    # get the 'in between' coordinates based on a '60fps' estimation
    steps = int(duration * 60) if duration else 0
    coordinates = _interpolate_coords(start_coords=start_coords,
                                      end_coords=end_coords,
                                      steps=steps)

    # send the mouse commands
    for x, y in coordinates:
        extra = ctypes.c_ulong(0)
        ii_ = Input_I()
        ii_.mi = MouseInput(x, y, 0, (0x0001 | 0x8000), 0,
                            ctypes.pointer(extra))
        x = Input(ctypes.c_ulong(0), ii_)
        ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))

        if duration:
            time.sleep(duration / len(coordinates))
Example #19
0
    def record_coords(self, event):
        '''Record mouse position at mouse press, and input coordinates into widgets'''
        cursorpos = GetCursorPos()

        if self.movement_relative.GetValue():
            # Set initial cursor position
            if not self.last_coord:
                self.coord_counter -= 1  # Negate the += 1 (this coordinate is origin, not position)
            else:
                # Set new point (all further positions derive from this)
                self._fill_coords(
                    [cursorpos[i] - self.last_coord[i] for i in [0, 1]])
            self.last_coord = cursorpos

        else:
            self._fill_coords(cursorpos)

        self.coord_counter += 1

        # Quit if all widgets have been filled
        if self.coord_counter == self.motionctrl.GetEffectiveRowsCount() - 1:
            self.stop_record()

        return True  # Needed for the hook manager
    def handle(self, command, *args, **kwargs):
        """ Execute a given command.
        :param command: string containing the command
        :param args: optional command args
        :param kwargs: optional command kwargs
        """

        if command == "run":
            self.__execute(args)
        elif command == "dictate":
            dictation_recorder = CommandRecorder()
            filename = "dictation.wav"
            log("Listening to dictation...")
            dictation_recorder.record_for_seconds(filename=filename, record_seconds=10)
            log("Dictation ended.")
            transcription = interpret_dication(filename)
            log("Transcription: ", transcription)
            remove(filename)
        elif command == "enter":
            SendKeys('{ENTER}')
        elif command == "home":
            SendKeys('{HOME}')
        elif command == "desktop":
            SendKeys('{LWIN}d')  # does it work?
        elif command == "next_window":
            SendKeys('%{ESC}')
        elif command == "up":
            scroll(coords=GetCursorPos(), wheel_dist=7)
        elif command == "down":
            scroll(coords=GetCursorPos(), wheel_dist=-7)
        elif command == "select_all":
            SendKeys('^a')
        elif command == "copy":
            SendKeys('^c')
        elif command == "paste":
            SendKeys('^v')
        elif command == "save":
            SendKeys('^s')
        elif command == "undo":
            SendKeys('^z')
        elif command == "find":
            SendKeys('^f')
            keyword_recorder = CommandRecorder()
            filename = "keyword.wav"
            log("What to find?")
            keyword_recorder.record_for_seconds(filename=filename, record_seconds=2)
            keyword = interpret_dication(filename)
            log("Szukam ", keyword)
            SendKeys(keyword[1:len(keyword) - 1] + '{ENTER}', with_spaces=True)
            remove(filename)
        elif command == "google":     # WIP
            app = Application(backend='uia')
            app.start(self.chrome_path + ' --force-renderer-accessibility https://www.google.com')
            keyword_recorder = CommandRecorder()
            filename = "keyword.wav"
            log("What to google?")
            keyword_recorder.record_for_seconds(filename=filename, record_seconds=3)
            keyword = interpret_dication(filename)
            log("Googling ", keyword)
            SendKeys(keyword[1:len(keyword)-1] + '{ENTER}', with_spaces=True)
            remove(filename)
        elif command == "youtube":
            app = Application(backend='uia')
            app.start(self.chrome_path + ' --force-renderer-accessibility https://www.youtube.com')
        elif command == "close":
            SendKeys('%{F4}')
        elif command == "end_commander":
            _exit(0)
        elif command == "yoda":
            app = Application(backend='uia')
            app.start(self.chrome_path + ' --force-renderer-accessibility https://youtu.be/bYRYHLUNEs4?t=18')
        elif command == "private_browsing":
            app = Application(backend='uia')
            app.start(self.chrome_path + ' --force-renderer-accessibility https://www.youtube.com/watch?v=x6QZn9xiuOE')
            SendKeys('^+n')
            SendKeys('chicks' + '{ENTER}', with_spaces=True)
            log("Have fun!")
        else:
            raise NotImplementedError('Unknown command!')
Example #21
0
def monitorWhereMousseIs():
    return str(MonitorFromPoint(GetCursorPos()))
Example #22
0
def test_wondering():
    start_x, start_y = GetCursorPos()
    main('miszka.py --delay 0.01 -i 1000 --no-anchor')
    x, y = GetCursorPos()
    assert abs(x - start_x) <= 10
    assert abs(y - start_y) <= 10
Example #23
0
    def __init__(self, controller):
        def on_close_game(button):
            WINDOW.dispatch_event('on_close')

        def on_iconify_game(button):
            WINDOW.minimize()

        def on_app_window_fullscreen(button):
            button.paired_button.opacity = button.opacity
            button.on_deactivate(instant=True)
            button.paired_button.on_activate()
            self.controller.on_fullscreen_button_click()

        def on_app_window_restore(button):
            button.paired_button.opacity = button.opacity
            button.on_deactivate(instant=True)
            button.paired_button.on_activate()
            self.controller.on_restore_button_click()

        def on_set_en_locale(button):
            self.controller.on_update_current_locale(ENGLISH)
            self.controller.on_update_clock_state(clock_24h_enabled=False)

        def on_set_ru_locale(button):
            self.controller.on_update_current_locale(RUSSIAN)
            self.controller.on_update_clock_state(clock_24h_enabled=True)

        super().__init__(controller, logger=getLogger('root.app.view'))
        self.shader_sprite = AppViewShaderSprite(view=self)
        self.title_label = AppTitleLabel(parent_viewport=self.viewport)
        self.fps_display = FPSDisplay(parent_viewport=self.viewport)
        self.us_flag_sprite = USFlagSprite(parent_viewport=self.viewport)
        self.ru_flag_sprite = RUFlagSprite(parent_viewport=self.viewport)
        self.close_game_button = CloseGameButton(on_click_action=on_close_game,
                                                 parent_viewport=self.viewport)
        self.iconify_button = IconifyButton(on_click_action=on_iconify_game,
                                            parent_viewport=self.viewport)
        self.fullscreen_button, self.restore_button = create_two_state_button(
            FullscreenButton(on_click_action=on_app_window_fullscreen,
                             parent_viewport=self.viewport),
            RestoreButton(on_click_action=on_app_window_restore,
                          parent_viewport=self.viewport))
        self.en_locale_button = ENLocaleButton(
            on_click_action=on_set_en_locale, parent_viewport=self.viewport)
        self.ru_locale_button = RULocaleButton(
            on_click_action=on_set_ru_locale, parent_viewport=self.viewport)
        self.buttons = [
            self.close_game_button, self.iconify_button,
            self.fullscreen_button, self.restore_button, self.en_locale_button,
            self.ru_locale_button
        ]
        self.on_window_resize_handlers.extend([
            *self.fps_display.on_window_resize_handlers,
            self.title_label.on_window_resize,
            self.shader_sprite.on_window_resize,
            self.us_flag_sprite.on_window_resize,
            self.ru_flag_sprite.on_window_resize
        ])
        self.on_append_window_handlers()
        self.app_window_move_mode = False
        self.app_window_move_offset = (0, 0)
        self.game_window_handler = GetActiveWindow()
        self.game_window_position = GetWindowRect(self.game_window_handler)
        self.absolute_mouse_pos = GetCursorPos()
        self.on_mouse_press_handlers.append(self.on_mouse_press)
        self.on_mouse_release_handlers.append(self.on_mouse_release)
        self.on_mouse_drag_handlers.append(self.on_mouse_drag)
        USER_DB_CURSOR.execute('SELECT fullscreen FROM graphics')
        self.fullscreen_mode = USER_DB_CURSOR.fetchone()[0]
        self.fullscreen_mode_available = False
        CONFIG_DB_CURSOR.execute(
            'SELECT app_width, app_height FROM screen_resolution_config')
        self.screen_resolution_config = CONFIG_DB_CURSOR.fetchall()
        if (windll.user32.GetSystemMetrics(0),
                windll.user32.GetSystemMetrics(1)
            ) in self.screen_resolution_config:
            self.fullscreen_mode_available = True
Example #24
0
resolution_w = GetSystemMetrics(0)
if string.atoi(vim.eval("g:enable_vim_wm_taskbar")) == 1:
    resolution_h = GetSystemMetrics(1) - 30
else:
    resolution_h = GetSystemMetrics(1)
hwnd = win32gui.GetActiveWindow()
win_rect = win32gui.GetWindowRect(hwnd)
win_rect_x = win_rect[0]
win_rect_y = win_rect[1]
win_rect_w = win_rect[2] - win_rect_x
win_rect_h = win_rect[3] - win_rect_y
center_x = (resolution_w - win_rect_w) / 2
center_y = (resolution_h - win_rect_h) / 2
smart_x = [resolution_w / 3 , resolution_w / 3 * 2 , resolution_w , resolution_w - win_rect_w]
smart_y = [resolution_h / 3 , resolution_h / 3 * 2 , resolution_h , resolution_h - win_rect_h]
wincenter = GetCursorPos()
if string.atoi(vim.eval("g:enable_vim_wm_smartsize")) == 1:
    big = [resolution_w / 3 * 2 , resolution_h / 3 * 2]
    large = [resolution_w / 5 * 4 , resolution_h / 5 * 4]
else:
    big = [string.atoi(vim.eval("g:vim_wm_big[0]")) , string.atoi(vim.eval("g:vim_wm_big[1]"))]
    large = [string.atoi(vim.eval("g:vim_wm_large[0]")) , string.atoi(vim.eval("g:vim_wm_large[1]"))]

def win_pos(x,y,z):
    win32gui.SetWindowPos(hwnd, 0, x, y, 0, 0, 0x0001 + 0x0004)
    vim.command("echo 'Position ='"+str(z))

def win_size(x,y):
    a = (resolution_w - x) / 2
    b = (resolution_h - y) / 2
    win32gui.SetWindowPos(hwnd, 0, a, b, x, y, 0x0004)
Example #25
0
def getPoints():
	global counter
	x, y = GetCursorPos()
	counter = counter + 1
	print('Point {0}:\tx={1}'.format(str(counter), str(x)), 'y=' + str(y))
Example #26
0
def MousePosition():
    X, Y = GetCursorPos()
    return X, Y
Example #27
0
def _test():
    from threading import Thread
    m = main()
    bg_cal = Thread(target = m.start)
    bg_cal.start()

    while True:
        print('{:.1f},{:.1f}, ({:.1f}, {:.1f}), ({:.1f}, {:.1f})'.format(m.dspeed,m.pixel_speed,GetCursorPos()[0],GetCursorPos()[1],m.posx,m.posy))
        sleep(0.2)
 def get_mouse__position():
     return GetCursorPos()
Example #29
0
 def get_cursor_pos(self):
     pt = GetCursorPos()
     self.logger.debug(f'cursor position is {pt}')
     return pt
Example #30
0
def display_splash_screen():
    import urllib.request
    import urllib.error
    from pywinauto_recorder.__init__ import __version__
    url_version = "https://raw.githubusercontent.com/beuaaa/pywinauto_recorder/master/bin/VersionInfo.rc"
    latest_version = __version__
    try:
        with urllib.request.urlopen(url_version) as f:
            line = f.read().decode('utf-8')
        latest_version = line.split('ProductVersion')[1].split('"')[2]
    except urllib.error.URLError:
        pass

    if __version__ == latest_version:
        print("Your Pywinauto recorder is up to date.")
    else:
        print("Pywinauto recorder v" + latest_version + " is available!")

    splash_foreground = oaam.Overlay(transparency=0.0)
    time.sleep(0.2)
    splash_background = oaam.Overlay(transparency=0.1)
    screen_width = GetSystemMetrics(0)
    screen_height = GetSystemMetrics(1)
    nb_band = 24
    line_height = 22.4
    text_lines = [''] * nb_band
    if __version__ == latest_version:
        text_lines[6] = 'Pywinauto recorder ' + __version__
    else:
        text_lines[
            6] = 'Your version of Pywinauto recorder (' + __version__ + ') is not up to date (' + latest_version + ' is available!)'
    text_lines[7] = 'by David Pratmarty'
    text_lines[
        9] = 'Record / Stop                            Smart mode On / Off'
    text_lines[
        10] = 'CTRL+ALT+R                                      CTRL+ALT+S'
    text_lines[12] = 'Search algorithm speed        Display / Hide information'
    text_lines[
        13] = '                                                       CTRL+SHIFT+D'
    text_lines[
        15] = 'Copy python code in clipboard          Click on "Quit" in'
    text_lines[
        16] = 'CTRL+SHIFT+F                                tray menu to quit'
    text_lines[
        18] = 'To replay your recorded file you can:                          '
    text_lines[19] = '- Drag and drop it on pywinauto_recorder.exe            '
    text_lines[
        20] = '- Click on "Start replaying clipboard" in tray menu       '
    text_lines[
        21] = '- Run "python.exe recorded_file.py"                           '

    splash_background.clear_all()
    w, h = 640, 540
    x, y = screen_width / 2 - w / 2, screen_height / 2 - h / 2
    splash_width = w
    splash_left = x
    splash_right = x + w
    splash_top = y
    splash_bottom = y + h
    splash_background.add(geometry=oaam.Shape.triangle,
                          thickness=0,
                          xyrgb_array=((x, y, 200, 0, 0),
                                       (x + w, y, 0, 128, 0), (x + w, y + h, 0,
                                                               0, 155)))
    splash_background.add(geometry=oaam.Shape.triangle,
                          thickness=0,
                          xyrgb_array=((x + w, y + h, 0, 0, 155),
                                       (x, y + h, 22, 128, 66), (x, y, 200, 0,
                                                                 0)))

    splash_background.refresh()

    mouse_was_splash_screen = False
    x, y = GetCursorPos()
    if (splash_left < x < splash_right) and (splash_top < y < splash_bottom):
        mouse_was_splash_screen = True
        message_to_continue = 'To continue: move the mouse cursor out of this window'
    else:
        message_to_continue = 'To continue: move the mouse cursor over this window'

    py_rec_icon_rect = (splash_left + splash_width / 2 - 200 / 2,
                        splash_top + 30, 200, 100)
    overlay_add_pywinauto_recorder_icon(splash_background, py_rec_icon_rect[0],
                                        py_rec_icon_rect[1])
    continue_after_splash_screen = True
    n = 0
    while continue_after_splash_screen:
        splash_foreground.clear_all()
        i = 0
        while i < nb_band:
            if i < 2:
                font_size = 44
            else:
                font_size = 20
            splash_foreground.add(x=splash_left,
                                  y=splash_top + i * line_height,
                                  width=splash_width,
                                  height=line_height,
                                  text=text_lines[i],
                                  font_size=font_size,
                                  text_color=(254, 255, 255),
                                  color=(255, 255, 255),
                                  geometry=oaam.Shape.rectangle,
                                  thickness=0)
            i = i + 1
        if n % 6 in [0, 1, 2]:
            _overlay_add_mode_icon(splash_foreground, IconSet.hicon_record,
                                   splash_left + 50,
                                   splash_top + line_height * 8.7)
        else:
            _overlay_add_mode_icon(splash_foreground, IconSet.hicon_stop,
                                   splash_left + 50,
                                   splash_top + line_height * 8.7)
        _overlay_add_mode_icon(splash_foreground, IconSet.hicon_light_on,
                               int(splash_right - (52 + 50)),
                               int(splash_top + line_height * 8.7))
        _overlay_add_progress_icon(splash_foreground, n % 6, splash_left + 50,
                                   splash_top + line_height * 11.7)
        _overlay_add_mode_icon(splash_foreground, IconSet.hicon_search,
                               int(splash_right - (52 + 50)),
                               splash_top + line_height * 11.7)
        _overlay_add_mode_icon(splash_foreground, IconSet.hicon_clipboard,
                               splash_left + 50,
                               splash_top + line_height * 14.7)
        _overlay_add_mode_icon(splash_foreground, IconSet.hicon_power,
                               int(splash_right - (52 + 50)),
                               splash_top + line_height * 14.7)
        _overlay_add_mode_icon(splash_foreground, IconSet.hicon_play,
                               splash_left + 50,
                               int(splash_top + line_height * 19.3))

        splash_foreground.refresh()
        time.sleep(0.4)
        if n % 2 == 0:
            text_lines[23] = message_to_continue
        else:
            text_lines[23] = ''
        continue_after_splash_screen = False
        x, y = GetCursorPos()
        if (splash_left < x < splash_right) and (splash_top < y <
                                                 splash_bottom):
            if mouse_was_splash_screen:
                continue_after_splash_screen = True
        else:
            if not mouse_was_splash_screen:
                continue_after_splash_screen = True
        n = n + 1
    splash_foreground.clear_all()
    splash_foreground.refresh()
    splash_background.clear_all()
    splash_background.refresh()