当用户在richtextbox中输入一个名字时,如何给列表上色

本文关键字:列表 一个 richtextbox 用户 输入 | 更新日期: 2023-09-27 18:17:00

我有一个名字列表,如"John", "Doe" ..等当用户在richtextbox中输入一个或多个时,我想给它们上色如果用户从名字中删除一个字母(比如"john"),这个单词的颜色就会改变恢复到原来的颜色

这是一个实验

  List<string> names = new List<string>
    {
        "john",
        "doe",
        "jack",
        "liza",
        "sandy",
        "sara"
    };

  private void richTextBox1_TextChanged(object sender, EventArgs e)
    {
        foreach (string name in names)
        {
            if (richTextBox1.Text.Contains(name))
            {
                var matchstring = Regex.Escape(name);
                foreach (Match match in Regex.Matches(richTextBox1.Text, matchstring))
                {
                    richTextBox1.Select(match.Index, match.Length);
                    richTextBox1.SelectionColor = Color.Red;
                    richTextBox1.Select(richTextBox1.TextLength, 0);
                    richTextBox1.SelectionColor = richTextBox1.ForeColor;
                }
            }
            else
            {
                richTextBox1.SelectAll();
                richTextBox1.SelectionColor = Color.Black;
                richTextBox1.Select(richTextBox1.TextLength, 0);
            }
        }
    }

当用户在richtextbox中输入一个名字时,如何给列表上色

下面是我上面评论的一个例子:

    private const int WM_SETREDRAW = 0xB;
    [System.Runtime.InteropServices.DllImport("user32.dll")]
    public static extern int SendMessage(IntPtr hWnd, Int32 wMsg, bool wParam, Int32 lParam);
    List<string> names = new List<string>
    {
        "john",
        "doe",
        "jack",
        "liza",
        "sandy",
        "sara"
    };
    private void richTextBox1_TextChanged(object sender, EventArgs e)
    {
        SendMessage(richTextBox1.Handle, WM_SETREDRAW, false, 0);
        int prevStart = richTextBox1.SelectionStart;
        int prevLength = richTextBox1.SelectionLength;
        richTextBox1.SelectAll();
        richTextBox1.SelectionColor = Color.Black;
        foreach (string name in names)
        {
            foreach (Match match in Regex.Matches(richTextBox1.Text, Regex.Escape(name)))
            {
                richTextBox1.Select(match.Index, match.Length);
                richTextBox1.SelectionColor = Color.Red;
            }
        }
        richTextBox1.Select(prevStart, prevLength);
        SendMessage(richTextBox1.Handle, WM_SETREDRAW, true, 0);
        richTextBox1.Invalidate();
    }

* WM_SETREDRAW调用是必要的,以减少闪烁的RichTextBox被更新。如果没有它们,当文本越来越长时,闪烁会变得非常明显。