Question

I would like specific content of a richTextBox after it was loaded mark colored (the `background 'of certain words change). When I click on a button to e.g. the word car to be marked. Now I found this code that I have to rebuild for my purposes.

public bool DoSearch(RichTextBox richTextBox, string searchText, bool searchNext)
       {
            TextRange searchRange;

            // Get the range to search
            if (searchNext)
                searchRange = new TextRange(richTextBox.Selection.Start.GetPositionAtOffset(1),
                                            richTextBox.Document.ContentEnd);
            else
                searchRange = new TextRange(richTextBox.Document.ContentStart, 
                                            richTextBox.Document.ContentEnd);

            // Do the search
            TextRange foundRange = FindTextInRange(searchRange, searchText);
            if (foundRange == null)
                return false;

            // Select the found range
            richTextBox.Selection.Select(foundRange.Start, foundRange.End);
            return true;
        }

        public TextRange FindTextInRange(TextRange searchRange, string searchText)
        {
            // Search the text with IndexOf
            int offset = searchRange.Text.IndexOf(searchText);
            if (offset < 0)
                return null;  // Not found

            // Try to select the text as a contiguous range
            for (TextPointer start = searchRange.Start.GetPositionAtOffset(offset); 
                             start != searchRange.End; 
                             start = start.GetPositionAtOffset(1))
            {
                TextRange result = new TextRange(start, start.GetPositionAtOffset(searchText.Length));
                if (result.Text == searchText)
                    return result;

            }
            return null;
        }

can someone help me?

Was it helpful?

Solution

Please try this link, contains a function HighlightPhrase which can change The Color of Specific Word in Rich textbox. Following this function try to investigate how to change background.

How to Change The Color of Specific Word in Rich textbox using C#

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top