C# find函数问题(不能高亮)

标签 c# winforms find richtextbox

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

目前,我能够找到用户输入的单词,但无法在 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!");
        }
    }

最佳答案

您正在使用 Find方法 - 这只是告诉您单词在文本框中的位置,它不会选择它。

您可以将 Find 的返回值与 Select 一起使用为了“突出”这个词:

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

或者,甚至更好(避免为单词搜索 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!");
}

关于C# find函数问题(不能高亮),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4264471/

相关文章:

c# - 如何在 Google Cloud 中使用 .Net Core 3.0 镜像?

c# - 简单数据绑定(bind)

c# - 保存 Winform 窗体控件状态的最佳方法?

bash - 如何在 bash 中按字母顺序对查找结果(包括嵌套目录)进行排序

c# - Azure Blob 存储 Blob 是否支持随机访问流?

c# - 如何比较两个 DateTimeOffSet?

c# - File.Copy 和 File.Move 的区别

winforms - 为什么Richtextbox无法正确显示此表?

带有目录/包的defineClass的Java ClassLoader格式?

c# - C# 中寻找最大值的最佳数据结构?