Highlight all searched words

后端 未结 6 755
耶瑟儿~
耶瑟儿~ 2020-12-16 00:35

In my RichtextBox, if I have written as below.

This is my pen,
his pen is beautiful.

Now I search word \"is\"

6条回答
  •  一向
    一向 (楼主)
    2020-12-16 01:05

    I would do it like that because all the other answers highlight the text, but doesnt change it back after you searched again.

    Use the RichText Find Method to find the starting index for the searching word.

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

    Use a Button or TextChangeListener and Search for your word.

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

    I would highly recommend to set a minimum word length to avoid freezing and high memory allocation.

提交回复
热议问题