【问题标题】:WinForm RichTextBox text color changes too many charactersWinForm RichTextBox 文字颜色改变太多字符
【发布时间】:2014-12-03 23:00:25
【问题描述】:

我已经在我的 winforms 应用程序中使用 rtf 盒子一段时间了,该应用程序作为我的外部硬件设备和我的 PC 之间的串行通信接口运行。我遇到的问题是,当使用任何颜色更改示例来选择文本(在我的实际命令之前通过串行发送)时,从我的外部设备返回的回声也发生了一些文本颜色更改。

发送符号';'我从我的设备中得到回声和响应,所有这些都以文本着色。

;;[UART+ERROR]

我的接收事件处理程序是标准的:

    private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
    {
        //fking threading
        string rxString = serialPort1.ReadExisting();    // running on worker thread

        this.Invoke((MethodInvoker)delegate
        {
            textLog.AppendText(rxString);    // runs on UI thread
        });
    }

为了写入屏幕,我使用了下面的示例(我也尝试过许多其他示例)来开始我的应用程序。我不确定自己做错了什么。

    private void AppendTextColor(RichTextBox box, Color color, string text)
    {
        int start = box.TextLength;
        box.AppendText(text);
        int end = box.TextLength;

        // Textbox may transform chars, so (end-start) != text.Length
        box.Select(start, end - start);
        {
            box.SelectionColor = color;
            // could set box.SelectionBackColor, box.SelectionFont too.
        }
        box.SelectionLength = 0; // clear
    }

【问题讨论】:

  • 所以你想通过颜色来区分命令和响应,命令文本的颜色是黑色(默认),响应是红色,但是当你将响应附加到 RichTextBox 时,命令文字也变红了?
  • 没错!这样做会让它们更容易阅读!
  • 您可以调用AppendTextColor来显示命令和响应,指定不同的颜色。如果只是调用AppendText显示响应,颜色不是默认颜色,而是设置为命令的颜色。想想 MS WORD,如果你设置一个选择的样式并在该选择之后键入,新内容的样式与选择的样式相同。

标签: c# .net winforms colors richtextbox


【解决方案1】:

您的 Select() 调用将 SelectionStart 属性留在附加文本的开头而不是文本的结尾。您可以像对 SelectionLength 所做的那样恢复它,但更简单的方法是:

    private static void AppendTextColor(RichTextBox box, Color color, string text) {
        box.SelectionStart = box.Text.Length;   // Optional
        var oldcolor = box.SelectionColor;
        box.SelectionColor = color;
        box.AppendText(text);
        box.SelectionColor = oldcolor;
    }

注意 // 可选注释,当用户无法编辑文本时不需要它。

请注意,您的代码中存在非常严重的消防软管问题。您正在以非常高的速率调用 Invoke(),当盒子开始填满时,可能会导致 UI 线程开始燃烧 100% 内核。很容易判断何时发生这种情况,您再也看不到更新,并且您的程序停止响应输入。需要在 DataReceived 事件处理程序中进行缓冲,使用 ReadLine() 而不是 ReadExisting() 通常是到达那里的简单方法。并改用 BeginInvoke(),Invoke()非常可能导致 SerialPort.Close() 调用死锁。

【讨论】:

    【解决方案2】:

    您需要将颜色重置为 RTB 的正常文本颜色:

    box.SelectionStart = box.Text.Length; // clear..
    box.SelectionLength = 0; // clear     // ..selection
    box.SelectionColor = box.ForeColor;   // reset color
    

    【讨论】:

      猜你喜欢
      • 2016-08-19
      • 2013-10-25
      • 1970-01-01
      • 2012-07-28
      • 2013-06-15
      • 2022-10-06
      • 2012-01-20
      • 2015-10-08
      • 2017-03-27
      相关资源
      最近更新 更多