Color different parts of a RichTextBox string

前端 未结 9 852
暖寄归人
暖寄归人 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:29

    Here is an extension method that overloads the AppendText method with a color parameter:

    public static class RichTextBoxExtensions
    {
        public static void AppendText(this RichTextBox box, string text, Color color)
        {
            box.SelectionStart = box.TextLength;
            box.SelectionLength = 0;
    
            box.SelectionColor = color;
            box.AppendText(text);
            box.SelectionColor = box.ForeColor;
        }
    }
    

    And this is how you would use it:

    var userid = "USER0001";
    var message = "Access denied";
    var box = new RichTextBox
                  {
                      Dock = DockStyle.Fill,
                      Font = new Font("Courier New", 10)
                  };
    
    box.AppendText("[" + DateTime.Now.ToShortTimeString() + "]", Color.Red);
    box.AppendText(" ");
    box.AppendText(userid, Color.Green);
    box.AppendText(": ");
    box.AppendText(message, Color.Blue);
    box.AppendText(Environment.NewLine);
    
    new Form {Controls = {box}}.ShowDialog();
    

    Note that you may notice some flickering if you're outputting a lot of messages. See this C# Corner article for ideas on how to reduce RichTextBox flicker.

提交回复
热议问题