Color different parts of a RichTextBox string

前端 未结 9 854
暖寄归人
暖寄归人 2020-11-22 08:10

I\'m trying to color parts of a string to be appended to a RichTextBox. I have a string built from different strings.

string temp = \"[\" + DateTime.Now.ToSh         


        
9条回答
  •  青春惊慌失措
    2020-11-22 08:53

    This is the modified version that I put in my code (I'm using .Net 4.5) but I think it should work on 4.0 too.

    public void AppendText(string text, Color color, bool addNewLine = false)
    {
            box.SuspendLayout();
            box.SelectionColor = color;
            box.AppendText(addNewLine
                ? $"{text}{Environment.NewLine}"
                : text);
            box.ScrollToCaret();
            box.ResumeLayout();
    }
    

    Differences with original one:

    • possibility to add text to a new line or simply append it
    • no need to change selection, it works the same
    • inserted ScrollToCaret to force autoscroll
    • added suspend/resume layout calls

提交回复
热议问题