1 Previous Next 

RichTextBox: Highlight words


This tip shows how to highlight all instances of a word in rich text box.  For this example you need a rich text box, textbox, and button on a form. 

This tip is by Spotty Bowles

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Me.RichTextBox1.Text = "this is a test of the test system"
    End Sub

    Function HighlightWords(ByVal rtb As RichTextBox, ByVal sFindString As String, ByVal lColor As System.Drawing.Color) As Integer

        Dim iFoundPos As Integer 'Position of first character of match
        Dim iFindLength As Integer       'Length of string to find
        Dim iOriginalSelStart As Integer
        Dim iOriginalSelLength As Integer
        Dim iMatchCount As Integer      'Number of matches

        'Save the insertion points current location and length
        iOriginalSelStart = rtb.SelectionStart
        iOriginalSelLength = rtb.SelectionLength

        'Cache the length of the string to find
        iFindLength = Len(sFindString)

        'Attempt to find the first match
        iFoundPos = rtb.Find(sFindString, 0, RichTextBoxFinds.NoHighlight)
        While iFoundPos > 0
            iMatchCount = iMatchCount + 1

            rtb.SelectionStart = iFoundPos
            'The SelLength property is set to 0 as soon as you change SelStart
            rtb.SelectionLength = iFindLength
            rtb.SelectionBackColor = lColor

            'Attempt to find the next match
            iFoundPos = rtb.Find(sFindString, iFoundPos + iFindLength, RichTextBoxFinds.NoHighlight)
        End While

        'Restore the insertion point to its original location and length
        rtb.SelectionStart = iOriginalSelStart
        rtb.SelectionLength = iOriginalSelLength

        'Return the number of matches
        HighlightWords = iMatchCount
    End Function


    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim icountMatch As Integer = 0
        icountMatch = HighlightWords(RichTextBox1, TextBox1.Text, System.Drawing.Color.Green)
        MessageBox.Show(icountMatch.ToString & " matches Found")
    End Sub
End Class




1 Previous Next