[英]Moving the mouse cursor asynchronous
I would like to know if there is any way to move the cursor without locking the UI thread in Winforms. 我想知道是否有任何方法移动光标而不锁定Winforms中的UI线程。 In other words;
换一种说法; an async solution.
异步解决方案。
My current synchronous solution: 我目前的同步解决方案
private void Form1_Load(object sender, EventArgs e)
{
TimeSpan delayt = new TimeSpan(0, 0, 3);
LinearSmoothMove(new Point(20, 40), delayt);
}
[DllImport("user32.dll")]
static extern bool SetCursorPos(int X, int Y);
public static void LinearSmoothMove(Point newPosition, TimeSpan duration)
{
Point start = Cursor.Position;
int sleep = 10;
double deltaX = newPosition.X - start.X;
double deltaY = newPosition.Y - start.Y;
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
double timeFraction = 0.0;
do
{
timeFraction = (double)stopwatch.Elapsed.Ticks / duration.Ticks;
if (timeFraction > 1.0)
timeFraction = 1.0;
PointF curPoint = new PointF((float)(start.X + timeFraction * deltaX),
(float)(start.Y + timeFraction * deltaY));
SetCursorPos(Point.Round(curPoint).X, Point.Round(curPoint).Y);
Thread.Sleep(sleep);
} while (timeFraction < 1.0);
}
You could use a Thread or a BackgroundWorker
like this: 您可以像这样使用Thread或
BackgroundWorker
:
BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += (s, ex) =>
{
SetCursorPos(0, 0);
};
bw.RunWorkerAsync();
you can use the BackgroundWorker
as romano said, but for that little function you can just use a timer: 您可以使用
BackgroundWorker
作为romano说,但对于这个小功能,您可以使用计时器:
private void Form1_Load(object sender, EventArgs e)
{
System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
timer.Interval = 10;
timer.Tick += new EventHandler(t_Tick);
timer.Start();
}
void OnTick(object sender, EventArgs e)
{
// Your code
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.