我想知道是否有任何方法可以在Winforms中锁定UI线程的情况下移动光标。换一种说法;异步解决方案。
我目前的同步解决方案:
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);
}
答案 0 :(得分:1)
你可以使用这样的线程或BackgroundWorker
:
BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += (s, ex) =>
{
SetCursorPos(0, 0);
};
bw.RunWorkerAsync();
答案 1 :(得分:1)
你可以使用BackgroundWorker
作为罗马说,但是对于那个小功能,你可以使用一个计时器:
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
}