Skip to content

Instantly share code, notes, and snippets.

@heiswayi
Last active December 21, 2016 15:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save heiswayi/22d9e5cbdd037c678660a28d3d2666f3 to your computer and use it in GitHub Desktop.
Save heiswayi/22d9e5cbdd037c678660a28d3d2666f3 to your computer and use it in GitHub Desktop.
C# code snippet - Making mouse cursor linear movement looks more realistic. Source: http://stackoverflow.com/a/913703/2019740
[DllImport("user32.dll")]
private static extern bool SetCursorPos(int X, int Y);
[DllImport("user32.dll")]
public static extern bool GetCursorPos(out Point p);
public static void LinearSmoothMove(Point newPosition, int steps)
{
Point start = new Point();
GetCursorPos(out start);
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);
SetCursorPos(Point.Round(iterPoint).X, Point.Round(iterPoint).Y);
Thread.Sleep(2);
}
// Move the mouse to the final destination.
SetCursorPos(newPosition.X, newPosition.Y);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment