简体   繁体   English

视觉工作室富文本框不显示文本

[英]visual studio richtext box not displaying text

I am using Visual studio 2017 and I have a RichTextBox that doesn't display text when I set it:我正在使用 Visual Studio 2017 并且我有一个 RichTextBox,它在我设置时不显示文本:

public void ArduinoDataRecived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{ 
    SerialPort TempSerial = (SerialPort)sender;
    ConsoleTextBox.AppendText(TempSerial.ReadLine());
}

The code runs with no errors and whenever I call the MessageBox.Show(ConsoleTextBox.text) it displays the text that the serial port sent and yet the text box doesn't display it.代码运行时没有错误,每当我调用MessageBox.Show(ConsoleTextBox.text)它都会显示串行端口发送的文本,但文本框不显示它。

If I have a completely different method that set the text then it works?如果我有一个完全不同的方法来设置文本,那么它有效吗?

Probably a threading issue.应该是线程问题。 Here's a copy-paste from the documentation :这是文档中的复制粘贴:

The DataReceived event is raised on a secondary thread when data is received from the SerialPort object.当从 SerialPort 对象接收数据时,在辅助线程上引发 DataReceived 事件。 Because this event is raised on a secondary thread, and not the main thread, attempting to modify some elements in the main thread, such as UI elements, could raise a threading exception.由于此事件是在辅助线程而非主线程上引发的,因此尝试修改主线程中的某些元素(例如 UI 元素)可能会引发线程异常。 If it is necessary to modify elements in the main Form or Control, post change requests back using Invoke, which will do the work on the proper thread.如果需要修改主 Form 或 Control 中的元素,请使用 Invoke 发回更改请求,这将在适当的线程上完成工作。

PS Before using System.IO.Ports.SerialPort be sure to read this . PS 在使用 System.IO.Ports.SerialPort 之前,请务必阅读此内容And this .而这个 Unfortunately, the problems are still not fixed in .NET 4.5.2.不幸的是,这些问题在 .NET 4.5.2 中仍未解决。 Not long ago I ported my serial comm code from C# to C++ to make my software work reliably for all users.不久前,我将我的串行通信代码从 C# 移植到 C++,以使我的软件为所有用户可靠地工作。 But if it works on your machine, and you're not working on a commercial software, System.IO.Ports.SerialPort might still be fine for you.但如果它适用于您的机器,并且您不是在使用商业软件,那么 System.IO.Ports.SerialPort 可能仍然适合您。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM