【问题标题】:RichTextBox selection and selection color not workingRichTextBox 选择和选择颜色不起作用
【发布时间】:2014-10-31 14:48:25
【问题描述】:

我有一个方法可以检测用户名,突出显示并更改其颜色,然后将其放入 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;
        }
    }

结果是我得到的所有文本都变回了红色。有什么我做错了或有什么原因导致它无法正常工作吗?

【问题讨论】:

  • 我想这是关于 Winforms 的。你的问题解决了吗?

标签: c# colors richtextbox


【解决方案1】:

您的错误是将按摩文本直接添加到 RichTextBox.Text 中。这会丢失或弄乱您之前获得的所有格式。

您必须使用专用函数AppendText

serverChat.AppendText(message);

serverChat.AppendText(Environment.NewLine);

这将保留以前的格式。

您的选择也有点偏离。当您以空文本开头并且用户名不正确时,它会崩溃。试试这个:

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】:

    我假设您想突出显示所有用户名,而不仅仅是最后一个。在这种情况下,您需要使用背景/前景色来实现您正在寻找的效果并且不要使用选择。基本上是使用 textrange + apply 属性的技巧。下面的链接应该有帮助

    How to properly apply backgroundcolor on a text in RichTextBox

    【讨论】:

    • 此链接到 WPF 帖子,但问题似乎与 Winforms RichTextBoxes 有关。
    猜你喜欢
    • 1970-01-01
    • 2012-08-18
    • 1970-01-01
    • 2014-12-17
    • 1970-01-01
    • 1970-01-01
    • 2020-04-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多