C# moving the mouse around realistically

后端 未结 5 1286
孤街浪徒
孤街浪徒 2020-12-02 21:44

I am demoing a piece of software and want to build a mouse \'mover\' function so that I can basically automate the process. I want to create realistic mouse movements but a

5条回答
  •  难免孤独
    2020-12-02 22:12

    I tried the arc calculation method, turned out to be far to complex and, in the end, it didn't look realistic. Straight lines look much more human, as JP suggests in his comment.

    This is a function I wrote to calculate a linear mouse movement. Should be pretty self-explanatory. GetCursorPosition() and SetCursorPosition(Point) are wrappers around the win32 functions GetCursorPos and SetCursorPos.

    As far as the math goes - technically, this is called Linear Interpolation of a line segment.

    public void LinearSmoothMove(Point newPosition, int steps) {
        Point start = GetCursorPosition();
        PointF iterPoint = start;
    
        // Find the slope of the line segment defined by start and newPosition
        PointF slope = new PointF(newPosition.X - start.X, newPosition.Y - start.Y);
    
        // Divide by the number of steps
        slope.X = slope.X / steps;
        slope.Y = slope.Y / steps;
    
        // Move the mouse to each iterative point.
        for (int i = 0; i < steps; i++)
        {
            iterPoint = new PointF(iterPoint.X + slope.X, iterPoint.Y + slope.Y);
            SetCursorPosition(Point.Round(iterPoint));
            Thread.Sleep(MouseEventDelayMS);
        }
    
        // Move the mouse to the final destination.
        SetCursorPosition(newPosition);
    }
    

提交回复
热议问题