【问题标题】:RichTextBox - Add text to top with multiple colors (only latest line is showing)RichTextBox - 使用多种颜色将文本添加到顶部(仅显示最新行)
【发布时间】:2013-09-07 06:09:50
【问题描述】:

我正在尝试复制一个日志窗口,所以最近的日志应该出现在顶部 - 最明显。因此,我需要在顶部添加一个文本(没问题)但有多种颜色(问题)。

首先我存储原始文本。 (它是 rtf 或文本 - 都试过了) 然后我添加新文本,带有用户名,然后是一条消息。用户名应该是一种颜色,而消息应该是另一种颜色。它也总是单行的。

我的方法是,在附加旧文本或旧 RTF 文本时,仅显示最新的“日志”。

public void AddLog(Log log)
{
        try
        {
            string oldText = this.richTextBox1.Rtf;

            this.richTextBox1.Text = log.User + ": " + log.Message + "\n";
            this.richTextBox1.Select(0, log.User.Length);
            this.richTextBox1.SelectionColor = Color.GreenYellow;
            this.richTextBox1.Select(log.User.Length + 2, log.Message.Length);
            this.richTextBox1.SelectionColor = Color.White;
            this.richTextBox1.DeselectAll();
            this.richTextBox1.Rtf += oldText;

        }
        catch { }
}

这甚至可能吗?因为它不保存旧的 RTF 文本,并且旧的 RTF 文本不能附加到新文本之后,这意味着我可能必须在下面添加最新的文本,这不是我想要的。

如果我不保存“RTF”文本,格式(颜色)将会消失,并且只会显示一种颜色。

【问题讨论】:

    标签: c# logging colors richtextbox


    【解决方案1】:

    未测试但试试这个

    public void AddLog(Log log)
    {
        try
        {
            richTextBox1.SelectAll();            
            string oldText = this.richTextBox1.SelectedRtf;
    
            this.richTextBox1.Text = log.User + ": " + log.Message + "\n";
            this.richTextBox1.Select(0, log.User.Length);
            this.richTextBox1.SelectionColor = Color.GreenYellow;
            this.richTextBox1.Select(log.User.Length + 2, log.Message.Length);
            this.richTextBox1.SelectionColor = Color.White;
            this.richTextBox1.DeselectAll();
            this.richTextBox1.SelectionStart = this.richTextBox1.TextLength;
            this.richTextBox1.SelectedRtf = oldText;
            this.richTextBox1.DeselectAll();
    
        }
        catch { }
    }
    

    【讨论】:

    • 是的,我不知道先选择 SelectedRtf 文本或仅复制 .Rtf 文本(格式化文本)然后再次添加有什么区别。但这有效。在添加新文本后,所有其他尝试都未格式化文本,或者由于某种原因变得奇怪。
    • 我的理解是Rtf 属性给出了完整的Rtf format,而SelectedRtf 给出了其中的一部分。我会这样说它与 HTML 相关。 Rtf + Rtf 就像 <html>sometags</html><html>sometags2</html> 插入 SelectedRtf 只影响子集所以 <html>sometags,sometags2</html>。结果,第一种格式会导致无效数据,而第二种则不会。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多