Highlight text in a richtextbox in windows forms

14,331

This code should do the work:

Dim searchstring As String = "hello"
' The word you're looking for
Dim count As New List(Of Integer)()
For i As Integer = 0 To richTextBox1.Text.Length - 1
    If richTextBox1.Text.IndexOf(searchstring, i) <> -1 Then
        'If the word is found
            'Add the index to the list
        count.Add(richTextBox1.Text.IndexOf(searchstring, i))
    End If
Next
Try
    For i As Integer = 0 To count.Count - 1

        richTextBox1.[Select](count(i), searchstring.Length)
        richTextBox1.SelectionFont = New Font(richTextBox1.Font, FontStyle.Bold)
        count.RemoveAt(i)
    Next
Catch
End Try
richTextBox1.[Select](richTextBox1.Text.Length, 0)
richTextBox1.SelectionFont = New Font(richTextBox1.Font, FontStyle.Regula

For each index select the text and make it bold.

Now add this code to the TextChanged-Event to check any time the text changed for your word.

Share:
14,331
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin almost 2 years

    How to make when i type in a RichTextBox a certain word it gets highlited?

    how do i find words in the text to use SelectionColor or SelectionFont

    For example: i want that all times that the word "hello" appear in the RichTextBox it turn to bold or turn into a color...

    Then if i open my program and type "hello, how are you?" the word hello turns into bold... any idea? (my idea is to make a text editor with syntax highlight that ill specify the words)

    (sorry if there is another question like that, i tried to search but i didn't find a answer that helped me)

    its windows forms, visual basic