线程读写控件需要用委托(delegate)与Invoke/BeginInvoke来进行
参考内容:http://www.cnblogs.com/runner/archive/2011/12/30/2307576.html
1. 获取TextBox中的值
代码一:
public delegate string GetTextBoxCallBack();
private string GetInputText()
{
try
{
if (this.txtInput.InvokeRequired)
{
GetTextBoxCallBack gtb = new GetTextBoxCallBack(GetInputText);
IAsyncResult ia = txtInput.BeginInvoke(gtb);
return (string)txtInput.EndInvoke(ia); //这里需要利用EndInvoke来获取返回值
}
else
{
return txtInput.Text;
}
}
catch (Exception ex)
{
return "";
}
}
代码二:
private string GetTextCallBack()
{
if (this.txtInput.InvokeRequired)
{
string inputTxt = string.Empty;
this.txtInput.Invoke(new MethodInvoker(delegate { inputTxt = txtInput.Text; }));
return inputTxt;
}
else
{
return this.txtInput.Text;
}
}
2.线程设置TextBox值
代码一:
delegate void SetTextBoxCallback(string text);
private void SetInputText(string text)
{
if (this.txtInput.InvokeRequired)
{
SetTextBoxCallback d = new SetTextBoxCallback(SetInputText);
this.Invoke(d, new object[] { text });
}
else
{
this.txtInput.Text = text;
}
}
代码二:
string changeTxt = "Change Text";
txtInput.Invoke(new Action<String>(p =>
{
txtInput.Text = changeTxt;
}), txtInput.Text);