RichTextBox-用多种颜色将文本添加到顶部(只显示最新的一行)

本文关键字:显示 最新 一行 顶部 颜色 添加 文本 RichTextBox- | 更新日期: 2023-09-27 18:30:07

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

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

通过我的方法,我得到的只是,当附加旧文本或旧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"文本,格式(颜色)将消失,只显示一种颜色。

RichTextBox-用多种颜色将文本添加到顶部(只显示最新的一行)

未测试,但尝试此

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 { }
}