views:

373

answers:

1

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.ToShortTimeString() + "] " + userid + " " + message +
                              Environment.NewLine;

This is what the message would look like once it is constructed.

[9:23pm] User: my message here.

I want everything within including the brackets [9:23] to be one color, 'user' to be another color and the message to be another color. Then the string appended to my RichTextBox.

How can I accomplish this?

+4  A: 

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.

Nathan Baulch
This is beautiful, very useful !
ohadsc
I tried the code in the C# corner article and it does work great!
ileon