Daniel Lip
Daniel Lip

Reputation: 11319

How to color richTextBox text in colors in the same line and then move to next line?

The class at the top of form1 :

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;

            if (!string.IsNullOrWhiteSpace(box.Text))
            {
                box.AppendText("\r\n" + text);
            }
            else
            {
                box.AppendText(text);
            }

            box.SelectionColor = box.ForeColor;
        }
    }

and how i'm using it :

this.Invoke(new Action(
delegate ()
{
    RichTextBoxExtensions.AppendText(richTextBox1, $"Created: {e.FullPath}", Color.GreenYellow);
    RichTextBoxExtensions.AppendText(richTextBox1, $" On: {DateTime.Now}", Color.Yellow);
}));

The problem is that it's adding two lines to the richTextBox one in GreenYellow and then a new line in Yellow.

but i want this to be in once line : GreenYellow and Yellow and then after that if adding another text that the new text to be in a new line.

This is a screenshot of how it is now :

as it is now

and this screenshot is ho i want it to be both on same line and after that if a new text will be added the new text will be in a new line :

as i want it to be

Upvotes: 1

Views: 77

Answers (1)

OldDog
OldDog

Reputation: 371

I think you need to reverse your logic from:

        if (!string.IsNullOrWhiteSpace(box.Text))
        {
            box.AppendText("\r\n" + text);
        }
        else
        {
            box.AppendText(text);
        }

To:

        if (!string.IsNullOrWhiteSpace(box.Text))
        {
            box.AppendText(text);
        }
        else
        {
            box.AppendText("\r\n" + text);
        }

Upvotes: 1

Related Questions