我接收数据时会提示错误: "线程间操作无效: 从不是创建控件“txtIn”的线程访问它." 错误指向"txtIn.Text = InputData;"那里..该怎么解决(txtIn是显示收到的数据的文本框...)
代码如下:
private void port_DataReceived_1(object sender, SerialDataReceivedEventArgs e)
{
InputData = port.ReadExisting();
if (InputData != String.Empty)
{
SetText(InputData);
txtIn.Text = InputData;
}
}
private void SetText(string text)
{
if (this.txtIn.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else this.txtIn.Text += text;
}
private void fclsRS232Tester_Load(object sender, EventArgs e)
{
}
代码如下:
private void port_DataReceived_1(object sender, SerialDataReceivedEventArgs e)
{
InputData = port.ReadExisting();
if (InputData != String.Empty)
{
SetText(InputData);
txtIn.Text = InputData;
}
}
private void SetText(string text)
{
if (this.txtIn.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else this.txtIn.Text += text;
}
private void fclsRS232Tester_Load(object sender, EventArgs e)
{
}
2. txtIn.Text = InputData;
调用了两遍设置文本,下面那个去掉
第三种就比较原始了:在类里面定义一个字段,每次串口收到数据就更新这个字段,然后在主线程里将这个字段更新显示到控件。就是多倒一次手了。