c#鼠标随机移动代码:
static void MoveMouseSmoothly()
{
Random random = new Random();
int randomNumber = random.Next(0, 20);
if(randomNumber != 9)
{
return;
}
Program.form_log("随机移动鼠标");
Rectangle screenBounds = Screen.PrimaryScreen.Bounds;
// 获取当前鼠标位置
Point currentPosition = Cursor.Position;
// 生成新的随机目标位置,稍微偏移当前鼠标位置
int targetX = currentPosition.X + random.Next(-100, 100); // 随机移动范围
int targetY = currentPosition.Y + random.Next(-100, 100);
// 限制目标位置在屏幕范围内
targetX = Math.Max(screenBounds.Left, Math.Min(screenBounds.Right, targetX));
targetY = Math.Max(screenBounds.Top, Math.Min(screenBounds.Bottom, targetY));
// 分步移动鼠标到目标位置
SmoothMoveCursor(currentPosition, new Point(targetX, targetY), 1000); // 移动时间 1000 毫秒
}
// 模拟平滑移动鼠标
static void SmoothMoveCursor(Point start, Point end, int duration)
{
int steps = 100; // 设定步数
int sleepTime = duration / steps; // 每步间隔的时间
for (int i = 0; i < steps; i++)
{
double t = (double)i / (double)steps;
// 计算每步的位置,并增加一些小的随机扰动
int x = (int)(start.X + (end.X - start.X) * t + random.Next(-3, 3));
int y = (int)(start.Y + (end.Y - start.Y) * t + random.Next(-3, 3));
Cursor.Position = new Point(x, y); // 设置鼠标位置
Thread.Sleep(sleepTime); // 暂停一小段时间,模拟自然移动
}
Cursor.Position = end; // 确保最终到达目标位置
}