Here's a sketch of some code which, I hope, will get you started.
Put a RichTextBox, a Button, and a TextBox on a WinForm: name them: 'richTextBox1, 'button1, and 'textBox1:
private string searchTerm;
private string theLine;
private int maxLines;
private int targetLine = 0;
private int matchAt;
private int searchTermLength;
private int lineLength;
private int lineOffset = 0;
private void button1_Click(object sender, EventArgs e)
maxLines = richTextBox1.Lines.Length;
searchTerm = textBox1.Text;
searchTermLength = searchTerm.Length;
theLine = richTextBox1.Lines[targetLine];
lineLength = theLine.Length;
matchAt = theLine.IndexOf(searchTerm);
richTextBox1.Select(lineOffset + matchAt, searchTermLength);
richTextBox1.SelectionBackColor = Color.Yellow;
lineOffset += lineLength + 1;
if (targetLine == maxLines)
targetLine = 0;
lineOffset = 0;
This code example will find, line by line, the first example of the search term in the RichTextBox, and highlight it yellow.
What it does not do is:
1. give any indication that it just checked a line which did not have the search term: if you want it to "skip over" lines that have no search term match, and automatically advance to the next line: that's left for you to do.
2. find multiple matches of the search term: that's left to you to figure out, but once you have "isolated" the current line, and have the information you can see calculated in the code: I believe that will not be difficult.
3. deal with the case where the RichTextBox content is changed, and you need to reset all the parameters for searching. And un-highlight any currently highlighted matches ?
4. deal with the case where the search term has changed, and you need to reset all the parameters for searching. And un-highlight any currently highlighted matches ?
5. any of the type of error-checking and validation a truly robust solution would do.
A really "robust" solution may need to keep track of all currently highlighted match terms, so it's easy to un-highlight them ? I might consider building a List<int> of each highlight match, where the integer value was the absolute value of the offset of the start of the match in the RichTextBox.Text: given the assumption that the search-term length is a constant, then all you need to do is execute a foreach loop through the generic List<int>, and select the high-lighted word, and reset the color.
Or, much more simply, just select all the Text in the RichTextBox and change its SelectionBackColor to some default value ?