0

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

首先,我存储原始文本。(它是 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”文本,格式(颜色)将消失并且只显示一种颜色。

4

1 回答 1

2

未测试,但试试这个

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 { }
}
于 2013-09-03T21:45:33.480 回答