2012-10-07 34 views
2

我在C#中學習線程,所以我的第一個程序將是2個將會移動的圖像。但問題是,我得到一個錯誤,當我嘗試在一個線程做一個新的起點:如何用線程移動PictureBox?

這裏是我的代碼:

namespace TADP___11___EjercicioHilosDatos 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     int x = 0; 
     int y = 0; 

     private void Form1_Load(object sender, EventArgs e) 
     { 
      Thread Proceso1 = new Thread(new ThreadStart(Hilo1)); 
      Proceso1.Start(); 
     } 

     public void Hilo1() 
     { 
      while (true) 
      { 
       x = pictureBox1.Location.X - 1; 
       y = pictureBox1.Location.Y; 
       pictureBox1.Location = new Point(x, y); 
      } 
     } 
    } 
} 

回答

3

Invoke它。出於[顯而易見的原因],您無法訪問由其他線程創建的控件,因此您必須使用委託。幾個類似的SO問題:

  1. How to update the GUI from another thread in C#?111 upvotes
  2. Writing to a textBox using two threads
  3. How to update textbox on GUI from another thread in C#
  4. Writing to a TextBox from another thread?

如果檢查出的第一個環節,伊恩最偉大的答案將演示如何你應該在.Net 2.0和3.0中做到這一點。或者你可以向下滾動到下一個答案,Marc's,它會告訴你如何以最簡單的方式做。

代碼:

//worker thread 
Point newPoint = new Point(someX, someY); 
this.Invoke((MethodInvoker)delegate { 
pictureBox1.Location = newPoint; 
// runs on UI thread 
}); 
6

您只能更新從控制上創建的線程控制。控件有一個Invoke方法,您可以從另一個線程調用。此方法需要一個委託,指定要控制的線程上做的工作:你有

var updateAction = new Action(() => { pictureBox1.Location = new Point(x,y); }); 
pictureBox1.Invoke(updateAction);