2012-12-26 48 views
0

這裏是我的示例代碼:RichTextBox的不跨線程操作更新

//------this is just GUI Form which is having RichTextBox (Access declared as Public) 
// 

public partial class Form1 : Form 
{ 
    public void function1() 
    { 
     ThreadStart t= function2; 
     Thread tStart= new Thread(t); 
     tStart.Start(); 
    } 

    public void function2() 
    { 
    //Calling function3 which is in another class 
    } 
} 


//------this is just Class, not GUI Form 
class secondClass: Form1 
{ 

    public void function3() 
    { 
     Form1 f =new Form1(); 
     //Updating the RichTextBox(which is created in Form1 GUI with Public access) 
     f.richTextBox1.AppendText("sample text"); 
    } 

} 

我試圖通過調用richTextBox1控制和運行我的代碼沒有錯誤,但richtextbox是不會得到更新。

我需要做什麼來更新我的狀態從richTextBox頻繁從另一個類功能?

回答

2

你porblem是在這裏:

public void function3() 
{ 
Form1 f =new Form1(); 
//Updating the RichTextBox(which is created in Form1 GUI with Public access) 
f.richTextBox1.AppendText("sample text"); 
} 

創建表單的另一個實例,並更改該richTextBox - 而不是最初的一個。

要完成這項工作,您應該使用Invoke方法,如here所示,在其代碼隱藏類中設置UI控件的值。來自其他類的函數應該使用任何輸入和輸出值的參數。

0

剛剛從Form1上通過你的RichTextBox到功能3

//function inside form1 
    public void function2() { 
     function3(this.richTextBox1); 
    } 

然後使用從另一個線程/類更新的RichTextBox調用

//function in another thread 
    public void function3(RichTextBox r) 
    { 
     r.InvokeIfRequired((value) => r.AppendText(value), "asd"); 
    }