富文本框控件中的自定义颜色 - C#

本文关键字:自定义 颜色 文本 控件 | 更新日期: 2023-09-27 18:32:15

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

富文本框控件中的自定义颜色 - C#

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

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();

看看这是否有帮助;

    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.
    }

好吧,老实说,这就像语法突出显示一样。但我希望它能帮助你。