简体   繁体   中英

Highlight word to find in VB.NET

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM