Highlight word to find in VB.NET

◇◆丶佛笑我妖孽 提交于 2020-02-01 09:59:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!