2013-08-06 166 views
0

我想知道是否有任何方法移動光標而不鎖定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); 
} 
+1

使用'定時器'? (至少這是最簡單的) –

+0

@KingKing是的,我希望有另一種選擇 – Johan

+0

至少比現在的解決方案更好。 –

回答

2

可以使用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 
    } 
1

你可以使用一個線程或BackgroundWorker這樣的:

 BackgroundWorker bw = new BackgroundWorker(); 

     bw.DoWork += (s, ex) => 
      { 
       SetCursorPos(0, 0); 
      }; 

     bw.RunWorkerAsync(); 
+0

據我所知,'BackgroundWorker'不會定期執行這項工作,爲了讓它以這種方式工作,您必須調用'Thread.Sleep(...)'?它不適合OP的問題。 –

+0

你說得對。我錯了他的問題。我以爲他真的需要在UI線程之外進行此操作。 –