RichTextBox控件中的自定义颜色 - C#

时间:2013-09-22 11:41:32

标签: c# richtextbox

我有一个函数,它以特定格式将文本附加到RichTextBox,然后仅为消息着色。这是功能:

 internal void SendChat(Color color, string from, string message)
        {
            if (rtbChat.InvokeRequired)
            {
                rtbChat.Invoke(new MethodInvoker(() => SendChat(color, from, message)));
                return;
            }

            string Text = String.Format("[{0}] {1}: {2}", DateTime.Now.ToString("t"), from, message);
            rtbChat.AppendText(Text);
            rtbChat.Find(message);
            rtbChat.SelectionColor = color;

            rtbChat.AppendText("\r\n");

            rtbChat.ScrollToCaret();
        }

输出如下:

[12:21 AM] Tester: Hello!

然而,当我输入一个小句子,例如2个字母时,有时颜色不会出现,有时也会出现。我担心它与Selection Color属性有关..有没有更好的方法来做或修复它?

2 个答案:

答案 0 :(得分:1)

尝试在添加消息时为文本着色:

rtbChat.AppendText(string.Format("[{0}] {1}: ", DateTime.Now.ToString("t"), from));
rtbChat.SelectionColor = color;
rtbChat.AppendText(message);
rtbChat.SelectionColor = Color.Black;
rtbChat.AppendText(Environment.NewLine);
rtbChat.ScrollToCaret();

答案 1 :(得分:0)

看看这是否有帮助;

    internal void SendChat(Color color, string from, string message)
    {
        if (rtbChat.InvokeRequired)
        {
            rtbChat.Invoke(new MethodInvoker(() => SendChat(color, from, message)));
            return;
        }

        string Text = String.Format("[{0}] {1}: {2}", DateTime.Now.ToString("t"), from, message);
        rtbChat.AppendText(Text);//Append text to rtbChat.
        //To speed up searching and highlighting text,its better to limit it to current line.
        int line = rtbChat.GetLineFromCharIndex(rtbChat.SelectionStart);//Get current line's number.
        string currenttext = rtbChat.Lines[line];//Get text of current line.
        Match match = Regex.Match(currenttext, message);//Find a match of the message in current text.
        if (match.Success)//If  message is found.
        {
            int position = rtbChat.SelectionStart;//Store caret's position before modifying it manually.
            rtbChat.Select(match.Index + rtbChat.GetFirstCharIndexFromLine(line), match.Length);//Select the match.
            rtbChat.SelectionColor = color;//Apply color code.
            rtbChat.SelectionStart = position;//Restore caret's position.
        }
        rtbChat.Text += Environment.NewLine;//Append a new line after each operation.
    }

嗯,说实话,这就像语法高亮。但我希望它能帮到你。