Richtextbox使用颜色添加新文本

时间:2016-06-29 11:09:21

标签: c# winforms richtextbox

我使用了richtextbox来在WinForms中显示日志。

使用的语言是C#。

该软件用于插入银行分行的数据,在新分行开始后,我想显示一个新颜色的文本。

我已看到链接Color different parts of a RichTextBox string并成功实施。

我的问题是我想要添加新行而不是追加。这就是新线将显示在顶部。

我可以通过将代码更改为box.Text=DateTime.Now.ToString("dd-MM-yyyy-hh-mm-ss") + ": " + text + box.Text

来完成此操作

但是整个文本的颜色正在发生变化。

这是用于追加

的程序
            box.SelectionStart = box.TextLength;
        box.SelectionLength = 0;

        box.SelectionColor = color;

        box.AppendText(DateTime.Now.ToString("dd-MM-yyyy-hh-mm-ss") + ": " + text);
        box.SelectionColor = box.ForeColor;

这就是我所做的:

            box.Text=DateTime.Now.ToString("dd-MM-yyyy-hh-mm-ss") + ": " + text + box.text;
        box.SelectionStart = 0;
        box.SelectionLength = text.length;
        box.SelectionColor = color;

但这不起作用。

2 个答案:

答案 0 :(得分:3)

1)从不直接更改已格式化的Text

RichtTextBox属性

2)要追加,请使用RTB.AppendText功能

3)插入在任何其他位置p,包括开头使用此内容:

rtb.SelectionStart = s;            // set the cursor to the target position
rtb.Selection.Length = 0;          // nothing selected, yet
rtb.SelectedText = yourNewText;    // this inserts the new text 

现在您可以添加所需的格式:

rtb.SelectionStart = s;            // now we prepare the new formatting..
rtb.SelectionLength = yourNewText.Length;   //.. by selecting the text
rtb.SelectionColor = Color.Blue;   // and/or whatever you want to do..
...

答案 1 :(得分:0)

    // Prepend, normal on first line, rest of lines gray italic

    private void PrependToRichTextbox(RichTextBox rt, string msg)
    {
        rt.SelectionStart = 0;
        rt.SelectionLength = 0;
        rt.SelectedText = msg + Environment.NewLine;

        int linecount = 0;
        foreach (var line in rt.Lines)
        {
            rt.Select(rt.GetFirstCharIndexFromLine(linecount), line.Length);
            rt.SelectionColor = linecount == 0 ? Color.Black : Color.Gray;
            Font currentFont = rt.SelectionFont;
            FontStyle newFontStyle;
            newFontStyle = linecount == 0 ? FontStyle.Regular : FontStyle.Italic;
            rt.SelectionFont = new Font(
               currentFont.FontFamily,
               currentFont.Size,
               newFontStyle
            );
            linecount++;
        }
    }