C# 線程獲取/設置控件(TextBox)值


線程讀寫控件需要用委托(delegate)與Invoke/BeginInvoke來進行

參考內容:http://www.cnblogs.com/runner/archive/2011/12/30/2307576.html

1. 獲取TextBox中的值

代碼一:

 1         public delegate string GetTextBoxCallBack();
 2         private string GetInputText()
 3         {
 4             try
 5             {
 6                 if (this.txtInput.InvokeRequired)
 7                 {
 8                     GetTextBoxCallBack gtb = new GetTextBoxCallBack(GetInputText);
 9                     IAsyncResult ia = txtInput.BeginInvoke(gtb);
10                     return (string)txtInput.EndInvoke(ia);  //這里需要利用EndInvoke來獲取返回值
11                 }
12                 else
13                 {
14                     return txtInput.Text;
15                 }
16             }
17             catch (Exception ex)
18             {
19                 return "";
20             }
21         }

 代碼二:

 1         private string GetTextCallBack()
 2         {
 3             if (this.txtInput.InvokeRequired)
 4             {
 5                 string inputTxt = string.Empty;
 6                 this.txtInput.Invoke(new MethodInvoker(delegate { inputTxt = txtInput.Text; }));
 7                 return inputTxt;
 8             }
 9             else
10             {
11                 return this.txtInput.Text;
12             }
13         }

 

2.線程設置TextBox值

代碼一:

 1         delegate void SetTextBoxCallback(string text);
 2         private void SetInputText(string text)
 3         {
 4             if (this.txtInput.InvokeRequired)
 5             {
 6                 SetTextBoxCallback d = new SetTextBoxCallback(SetInputText);
 7                 this.Invoke(d, new object[] { text });
 8             }
 9             else
10             {
11                 this.txtInput.Text = text;
12             }
13         }

 代碼二:

1 string changeTxt = "Change Text";
2 txtInput.Invoke(new Action<String>(p =>
3                 {
4                     txtInput.Text = changeTxt;
5                 }), txtInput.Text);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM