我的问题是要更改很多 TextBox.text 的另一个线程而不是 UI 线程。像这样:
string bufferSerial;
.
.
.
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
bufferSerial += serialPort1.ReadLine();
TextBox1.text = bufferSerial;
TextBox2.text = bufferSerial;
TextBox3.text = bufferSerial;
TextBox4.text = bufferSerial;
TextBox5.text = bufferSerial;
TextBox6.text = bufferSerial;
TextBox7.text = bufferSerial;
.
.
.
.
.
.
TextBoxN.text = bufferSerial;
}
如果我尝试这样做,我有一个错误:控件'textBox1'从创建它的线程以外的线程访问。
要更改单个 TextBox,我可以使用此解决方案:
delegate void SetTextCallback(string text);
private void SetText(string text)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (this.textBox1.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.textBox1.Text = text;
}
}
然后像这样调用函数:
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
bufferSerial += serialPort1.ReadLine();
SetText(bufferSerial);
}
但是如果我需要更改很多 BoxText 我必须为每个创建一个函数?
谢谢你的帮助!此致。