2012-04-13 34 views
0

我想要做的是在當前窗體的某個位置獲取像素顏色。但是,我稱之爲方法的地方在於單獨的線程。當我運行應用程序,我得到一個錯誤:在靜態多線程實例中調用

Cross-thread operation not valid: Control 'Form1' accessed from a thread other than the thread it was created on.

線程代碼:

Thread drawThread; 
drawThread = new Thread(drawBikes); 

drawBikes代碼:

public void drawBikes() 
{ 
    MessageBox.Show("Bike "+bike.color.ToString()+": "+Form1.ActiveForm.GetPixelColor(bike.location.X, bike.location.Y).ToString()); 
} 

這裏是GetPixelColor方法(在一個單獨的靜態類) :

public static class ControlExts 
{ 
    public static Color GetPixelColor(this Control c, int x, int y) 
    { 
     var screenCoords = c.PointToScreen(new Point(x, y)); 
     return Win32.GetPixelColor(screenCoords.X, screenCoords.Y); 
    } 
} 

我在哪裏調用Invoke?

+1

的數以百萬計的問題Dublicate http://stackoverflow.com/questions/22356/cleanest-way-to- invoke-cross-thread-events – 2012-04-13 18:26:32

+0

@ LB疑問報告的問題數量,但.. :) – Tigran 2012-04-13 18:46:30

回答

1

您需要從任何其他正在與UI進行交互的線程中調用Invoke。在你的情況,drawBikes()試圖更新用戶界面。試試這個:

public void drawBikes() 
    { 
     if (InvokeRequired) 
     { 
      this.Invoke(new MethodInvoker(drawBikes)); 
      return; 
     } 
     // code below will always be on the UI thread 
     MessageBox.Show("Bike "+bike.color.ToString()+": "+Form1.ActiveForm.GetPixelColor(bike.location.X, bike.location.Y).ToString()); 

    } 
0

把你的代碼中BeginInvoke

喜歡的東西

  public static class ControlExts 
      { 
         public static Color GetPixelColor(this Control c, int x, int y) 
         { 
         this.BeginInvoke(new Action(() => 
          { 
          var screenCoords = c.PointToScreen(new Point(x,y)); 
          return Win32.GetPixelColor(screenCoords.X, screenCoords.Y); 
         })); 

         } 
      }