0

我有一个以某种格式将文本附加到 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 个字母,有时颜色不会出现,有时会出现。我担心它与选择颜色属性有关。有没有更好的方法来做到这一点或修复它?

4

2 回答 2

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();
于 2013-09-22T12:32:27.413 回答
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.
    }

好吧,老实说,这有点像语法高亮。但我希望它会对你有所帮助。

于 2013-09-22T13:07:02.650 回答