How to simulate a mouse click and drag?
Asked Answered
B

2

7

I want to simulate an event where I left click on the Windows desktop, I drag the mouse a little to create a Selection box to another point, and then keep holding the left button at that point for some time without the Selection box disappearing.

The problem is, I can't get him to keep the Selection box, whenever he gets to the other point the Selection box disappears indicating that the button has been released.

I tried to implement in Python using PyAutoGUI. I tried several ways to do this but still unsuccessfully. Is there any function I'm missing?

import time
import pyautogui

time.sleep(3)

while True:
    pyautogui.moveTo(1080, 380)
    pyautogui.mouseDown(button='left')
    pyautogui.dragTo(917, 564, 1, button='left')
    time.sleep(10)
    pyautogui.mouseUp(button='left')
    time.sleep(2)
Botany answered 1/8, 2019 at 23:35 Comment(2)
@Erik Lopes Did you find a solution for this?Lunation
Anyone got the answer?Suppurative
L
8

Simply removing 2 lines of code and changing dragTo() to moveTo() seems to do what you are trying to do:

import time
import pyautogui

time.sleep(3)

while True:
    pyautogui.moveTo(1080, 380)
    pyautogui.mouseDown(button='left')
    pyautogui.moveTo(917, 564, 1)
    time.sleep(10)
Locoism answered 12/6, 2020 at 20:59 Comment(3)
I have a similar task but can't solve it with the solution provided by @Alt. I tried it also with dragTo() and drag(), but the mouse is clicked only for a short while not the whole way it should be kept clicked down.Lunation
@jason-m Kind of, I finally realized that the problem wasn't pyautogui but the application I wanted to use it with. I wanted to draw something on a picture opened with the Window Photo Viewer. There, it didn't work. With other applications (p.ex. MS Paint) it worked with the solution provided by Alt.Lunation
this worked for this thanks!Suppurative
S
3

This might help you a bit:

pyautogui.moveTo(1277, 127)

pyautogui.dragTo(1277, 225, button='left', duration=5)

(duration is in seconds)

Senility answered 18/12, 2021 at 17:23 Comment(2)
It is better to accompany your code with some explanations to help readers understand what your code does and why/how it solves the problemKurt
I think it's pretty self-explanatoryKevin

© 2022 - 2024 — McMap. All rights reserved.