问题
I have a RichTextBox (the text where I need to find all the word corresponds to the TextBox), TextBox (for typing the word to find) and a Button, and when I click on the Button, I would like that in the RichTextBox, all the words corresponding to the word written in the TextBox are highlighted with a color (yellow for example). I know how to find the first occurrence of the word but I do not know how to find all the occurrences.
The code for highlighting only the first occurrence of the word:
'CodeCS is my RichTextBox
CodeCS.SelectionBackColor = Color.White
CodeCS.Find(ToolStripTextBox1.Text, RichTextBoxFinds.MatchCase)
CodeCS.SelectionBackColor = Color.Yellow
回答1:
Here a simple loop over the searched text (rtb is the RichTextBox to search the text for)
Sub HighlightWord(searchText As String)
Dim len = searchText.Length
Dim pos = rtb.Find(searchText, 0, RichTextBoxFinds.NoHighlight)
While (pos >= 0)
rtb.Select(pos, len)
rtb.SelectionBackColor = Color.Yellow
if pos + len >= rtb.Text.Length Then
Exit While
End If
pos = rtb.Find(searchText, pos + len, RichTextBoxFinds.NoHighlight)
End While
End Sub
来源:https://stackoverflow.com/questions/44609110/highlight-word-to-find-in-vb-net