C# moving the mouse around realistically

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);
}

Leave a Comment