Search code examples
windowspython-3.xpywin32

How Do I move my mouse with flexible speed


I read something about pywin32 with give's you the possibility to move the curser to One Point to another.

How would I Click on one point and move it with a specific speed to another direction without the cursor "jumping" to that direction? I want a result where you could see what points it has passed.

OS is Windows.


Solution

  • Say you have two points, a start and a stop; you can calculate the line equation between them and just call win32api.SetCursorPos multiple times to animate the movement.

    import win32api, time
    
    def moveFromTo(p1, p2):
        # slope of our line
        m = (p2[1] - p1[1]) / (p2[0] - p1[0])
        # y intercept of our line
        i = p1[1] - m * p1[0]
        # current point
        cP = p1
        # while loop comparison
        comp = isGreater
        # moving left to right or right to left
        inc = -1
        # switch for moving to right
        if (p2[0] > p1[0]):
            comp = isLess
            inc = 1
        # move cursor one pixel at a time
        while comp(cP[0],p2[0]):
            win32api.SetCursorPos(cP)
            cP[0] += inc
            # get next point on line
            cP[1] = m * cP[0] + i
            # slow it down
            time.sleep(0.01)
    
    def isLess(a,b):
        return a < b
    def isGreater(a,b):
        return a > b
    
    moveFromTo([500,500],[100,100])