Domoq
Domoq

Reputation: 25

RichTextBox selection and selection color not working

I have a method that detects the username, highlights it and changes it's color and then puts it in the RichTextBox:

    private void displayMessage(string message, string color)
    {
        string username = message.Substring(0, message.IndexOf(':') - 1);
        string realMessage = message.Replace(username , "");

        serverChat.Text += message;
        serverChat.Select(((serverChat.Text.Length - message.Length) - 1), username.Length - 1);

        serverChat.SelectionColor = getColor(color);
        serverChat.Text += Environment.NewLine;
    }

    private void sendButton_Click(object sender, EventArgs e)
    {
        displayMessage("PersonX: Hey is it working for you?", "1");
        displayMessage("PersonY: Yeah, it just started. Thanks!", "0");
    }
    private Color getColor(string index)
    {
        switch (index)
        {
            case "0":
                return Color.Red;
            case "1":
                return Color.Blue;
            case "2":
                return Color.Green;
            case "3":
                return Color.Yellow;
            case "4":
                return Color.Black;
            default:
                return Color.Black;
        }
    }

The results is that I get all of the text coming back the color red. Is there anything that I did wrong or any reason that it would not be working?

Upvotes: 1

Views: 3656

Answers (2)

TaW
TaW

Reputation: 54433

Your mistake is to add the message text to the RichTextBox.Text dircetly. This will loose or mess up all the formatting you had achieved before.

Instead you must use the specialized function AppendText:

serverChat.AppendText(message);

and

serverChat.AppendText(Environment.NewLine);

This will keep the previous formatting.

Also your selection is a bit off. It crashes when you start with an empty text and doesn't quite get the usernames right. Try this:

string username = message.Substring(0, message.IndexOf(':') );
string realMessage = message.Replace(username , "");
serverChat.AppendText(message);
serverChat.Select(((serverChat.Text.Length - message.Length)), username.Length );
//..

Upvotes: 2

asb
asb

Reputation: 823

I am assuming you want to give all the user names as highlighted and not just the last one. In that case you need use the background/foreground colors to achieve the effect you are looking for and don't use the selection. Basically a trick using textrange + apply property. Below link should help

How to properly apply backgroundcolor on a text in RichTextBox

Upvotes: 0

Related Questions