1

我的问题是要更改很多 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 我必须为每个创建一个函数?

谢谢你的帮助!此致。

4

1 回答 1

0

不,创建一个更改所有文本框的方法 - 并调用它:

// We assume this will always be called from a non-UI thread...
private void HandleDataReceived(object sender, SerialDataReceivedEventArgs e)
{
    bufferSerial += serialPort1.ReadLine();
    Action<string> d = SetAllTextBoxes;
    Invoke(d, bufferSerial);
}

private void SetAllTextBoxes(string text)
{
    textBox1.Text = text;
    textBox2.Text = text;
    textBox3.Text = text;
    textBox4.Text = text;
    ...
}

理想情况下,您会将文本框放在一个集合中,以便您可以将其重写为:

private void SetAllTextBoxes(string text)
{
    foreach (var textBox in textBoxes)
    {
        textBox.Text = text;
    }
}
于 2013-03-02T14:51:26.173 回答