Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Highlight text in a richtextbox in windows forms

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


1 Answers

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.

like image 190
jAC Avatar answered Oct 31 '25 23:10

jAC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!