RichTextBox选择和选择颜色不起作用 [英] RichTextBox selection and selection color not working

查看:67
本文介绍了RichTextBox选择和选择颜色不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种方法可以检测用户名,将其突出显示并更改其颜色,然后将其放入RichTextBox中:

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?

推荐答案

您的错误是添加了按摩文字直接发送到RichTextBox.Text。

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.

相反,您必须使用特殊功能 AppendText

Instead you must use the specialized function AppendText:

serverChat.AppendText(message);

serverChat.AppendText(Environment.NewLine);

这将保留以前的格式。

此外,您的选择还有点不足。当您以空文本开头并且用户名输入不正确时,它会崩溃。尝试以下操作:

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 );
//..

这篇关于RichTextBox选择和选择颜色不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆