【问题标题】:Highlight all searched words突出显示所有搜索词
【发布时间】:2012-08-04 19:38:59
【问题描述】:

在我的RichtextBox,如果我写如下。

这是我的笔,
他的笔很漂亮。

现在我搜索单词“is”然后 输出如下。

所有“是”都应突出显示。

【问题讨论】:

  • 也应该突出显示“This”和“his”中的“is”?
  • 你能澄清一下目标平台吗? WPF 中有一个RichTextBox 不适用于已接受的解决方案。

标签: c# winforms find richtextbox highlight


【解决方案1】:

怎么样:

static class Utility {
    public static void HighlightText(this RichTextBox myRtb, string word, Color color) {  

       if (word == string.Empty)
            return;

       int s_start = myRtb.SelectionStart, startIndex = 0, index;

       while((index = myRtb.Text.IndexOf(word, startIndex)) != -1) {
           myRtb.Select(index, word.Length);
           myRtb.SelectionColor = color;

           startIndex = index + word.Length;
       }

       myRtb.SelectionStart = s_start;
       myRtb.SelectionLength = 0;
       myRtb.SelectionColor = Color.Black;
    }
}

【讨论】:

  • 你为什么要从 startIndex 位置搜索两个单词:while(myRtb.Text.IndexOf(word, startIndex) != -1){ int index = myRtb.Text.IndexOf(word, startIndex);?我认为你应该在 while 循环中保存找到的索引。
【解决方案2】:

看起来这样就可以了。

http://www.dotnetcurry.com/ShowArticle.aspx?ID=146

int start = 0;
int indexOfSearchText = 0;

    private void btnFind_Click(object sender, EventArgs e)
    {
        int startindex = 0;

        if(txtSearch.Text.Length > 0)
            startindex = FindMyText(txtSearch.Text.Trim(), start, rtb.Text.Length);

        // If string was found in the RichTextBox, highlight it
        if (startindex >= 0)
        {
            // Set the highlight color as red
            rtb.SelectionColor = Color.Red;
            // Find the end index. End Index = number of characters in textbox
            int endindex = txtSearch.Text.Length;
            // Highlight the search string
            rtb.Select(startindex, endindex);
            // mark the start position after the position of
            // last search string
            start = startindex + endindex;
        }
    }

    public int FindMyText(string txtToSearch, int searchStart, int searchEnd)
    {
        // Unselect the previously searched string
        if (searchStart > 0 && searchEnd > 0 && indexOfSearchText >= 0)
        {
            rtb.Undo();
        }

        // Set the return value to -1 by default.
        int retVal = -1;

        // A valid starting index should be specified.
        // if indexOfSearchText = -1, the end of search
        if (searchStart >= 0 && indexOfSearchText >=0)
        {
            // A valid ending index
            if (searchEnd > searchStart || searchEnd == -1)
            {
                // Find the position of search string in RichTextBox
                indexOfSearchText = rtb.Find(txtToSearch, searchStart, searchEnd, RichTextBoxFinds.None);
                // Determine whether the text was found in richTextBox1.
                if (indexOfSearchText != -1)
                {
                    // Return the index to the specified search text.
                    retVal = indexOfSearchText;
                }
            }
        }
        return retVal;
    }

// Reset the richtextbox when user changes the search string
    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        start = 0;
        indexOfSearchText = 0;
    }

【讨论】:

  • 这只会找到第一次出现,我想突出显示所有匹配的单词
【解决方案3】:

这将同时显示所有搜索条件。

使用:1 个文本框(用于输入要搜索的文本)和 1 个按钮(用于运行搜索)。

在文本框中输入您的搜索条件,然后按搜索按钮。

        // On Search Button Click: RichTextBox ("rtb") will display all the words inside the document
    private void btn_Search_Click(object sender, EventArgs e)
    {
        try
        {
            if (rtb.Text != string.Empty)
            {// if the ritchtextbox is not empty; highlight the search criteria
                int index = 0;
                String temp = rtb.Text;
                rtb.Text = "";
                rtb.Text = temp;
                while (index < rtb.Text.LastIndexOf(txt_Search.Text))
                {
                    rtb.Find(txt_Search.Text, index, rtb.TextLength, RichTextBoxFinds.None);
                    rtb.SelectionBackColor = Color.Yellow;
                    index = rtb.Text.IndexOf(txt_Search.Text, index) + 1;
                    rtb.Select();
                }
            }
        }

        catch (Exception ex) { MessageBox.Show(ex.Message, "Error"); }
    }
}

}

【讨论】:

    【解决方案4】:

    如果您只想匹配整个单词,您可以使用它,请注意这会忽略大小写,|s\b 表示复数会突出显示,例如猫匹配猫,但不匹配毛毛虫:

        public static void HighlightText(RichTextBox myRtb, string word, Color color)
        {
            if (word == string.Empty)
                return;
            var reg = new Regex(@"\b" + word + @"(\b|s\b)",RegexOptions.IgnoreCase);
    
            foreach (Match match in reg.Matches(myRtb.Text))
            {
                myRtb.Select(match.Index, match.Length);
                myRtb.SelectionColor = color;
            }
    
            myRtb.SelectionLength = 0;
            myRtb.SelectionColor = Color.Black;
        }
    

    【讨论】:

      【解决方案5】:
          private void button3_Click(object sender, EventArgs e)
          {
              if (textBox1.Text != "")
              {
                  for (int i = 0; i < richTextBox1.TextLength; i++)
                  {
                      richTextBox1.Find(textBox1.Text, i, RichTextBoxFinds.None);
                      richTextBox1.SelectionBackColor = Color.Red;
                  }
              }
              else
              {
                  for (int i = 0; i < richTextBox1.TextLength; i++)
                  {
                      richTextBox1.SelectAll();
                      richTextBox1.SelectionBackColor = Color.White;
                  }
              }
          }[lets make it!][1]
      

      【讨论】:

      • 请解释您的答案,而不仅仅是提供代码。此外,虽然您的解决方案似乎有效,但这个问题已经很老了,并且已经有了一个公认的答案。对新问题的帮助将更加感激:)
      • 确定。感激不尽
      • 您可以在帮助中心找到很多关于本站如何运作的信息,例如:如何回答:stackoverflow.com/help/how-to-answer
      【解决方案6】:

      我会这样做,因为所有其他答案都会突出显示文本,但在您再次搜索后不会将其更改回来。

      使用 RichText 查找方法查找搜索词的起始索引。

      public int FindMyText(string searchText, int searchStart, int searchEnd)
          {
              int returnValue = -1;
      
              if (searchText.Length > 0 && searchStart >= 0)
              {
                  if (searchEnd > searchStart || searchEnd == -1)
                  {
                      int indexToText = richTextBox1.Find(searchText, searchStart, searchEnd, RichTextBoxFinds.MatchCase);
                      if (indexToText >= 0)
                      {
                          returnValue = indexToText;
                      }
                  }
              }
      
              return returnValue;
          }
      

      使用 Button 或 TextChangeListener 并搜索您的单词。

      private void button1_Click(object sender, EventArgs e)
      {
              // Select the first char in your Richtextbox
              richTextBox1.SelectionStart = 0;
      
              richTextBox1.SelectionLength = richTextBox1.TextLength;
              // Select until the end
              richTextBox1.SelectionColor = Color.Black;
              // Make the Text Color black
      
              //Use an Inputfield to add the searching word
              var word = txtSearch.Text;
              //verify the minimum length otherwise it may freeze if you dont have text inside
              if (word.Length > 3)
              {
                int s_start = richTextBox1.SelectionStart, startIndex = 0, index;
                while ((index = FindMyText(word, startIndex, richTextBox1.TextLength)) != -1)
                  {
                  // goes through all possible found words and color them blue (starting index to end)
                      richTextBox1.Select(index, word.Length);
                      richTextBox1.SelectionColor = Color.Blue;
                      startIndex = index + word.Length;
                  }
                  // Color everything between in color black to highlight only found words       
                  richTextBox1.SelectionStart = startIndex;
                  richTextBox1.SelectionLength = 0;
                  richTextBox1.SelectionColor = Color.Black;
              }
      }
      

      我强烈建议设置最小字长以避免冻结和高内存分配。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-06-03
        • 2017-01-23
        • 2012-05-21
        • 2020-07-12
        • 2014-02-13
        • 2015-01-28
        相关资源
        最近更新 更多