RichTextBox selection and selection color not working

早过忘川 提交于 2019-12-08 09:18:08

问题


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?


回答1:


Your mistake is to add the massage 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 );
//..



回答2:


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



来源:https://stackoverflow.com/questions/25706372/richtextbox-selection-and-selection-color-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!