C#查找功能问题(无法突出显示)

ath*_*gap 1 c# richtextbox find winforms

我想问为什么我的代码不起作用?

目前,我能够找到用户输入的单词,但它无法突出显示richTextBoxConversation中的单词.

我应该怎么做呢?

以下是我的代码:

    private void buttonTextFilter_Click(object sender, EventArgs e)
    {
        string s1 = richTextBoxConversation.Text.ToLower();
        string s2 = textBoxTextFilter.Text.ToLower();

        if (s1.Contains(s2))
        {
            MessageBox.Show("Word found!");
            richTextBoxConversation.Find(s2);
        }
        else
        {
            MessageBox.Show("Word not found!");
        }
    }
Run Code Online (Sandbox Code Playgroud)

Ode*_*ded 6

您正在使用的Find方法-这只是告诉你哪里的字存在的文本框,它不会选择它.

您可以使用返回值从FindSelect以"亮点"字:

if (s1.Contains(s2))
{
  MessageBox.Show("Word found!");
  int wordPosition = richTextBoxConversation.Find(s2); // Get position
  richTextBoxConversation.Select(wordPosition, s2.Length);
}
Run Code Online (Sandbox Code Playgroud)

或者,甚至更好(避免搜索s1两次单词):

int wordPosition = richTextBoxConversation.Find(s2); // Get position
if (wordPosition > -1)
{
  MessageBox.Show("Word found!");
  richTextBoxConversation.Select(wordPosition, s2.Length);
}
else
{
  MessageBox.Show("Word not found!");
}
Run Code Online (Sandbox Code Playgroud)