Ron
Ron

Reputation: 391

Change color of all instances of a Word(s) in RichTextBox

Im trying to make it so, I can Specify a word or words in the code, and When I compile/debug I want the Program to search a richtextbox for all instances of those words and change there color.

Dim GRAB as String = New WebClient().DownloadString("example.com")
RichTextBox1.Text = GRAB
` Color Word Code Here

Ive looked up alot of things on google, but Everything I've tried will only highlight the FIRST word.

Sorry if my typing is bad, im typing with a broken arm..

Can someone help me with this, or write a quick snippet?

Upvotes: 1

Views: 3488

Answers (3)

r3play
r3play

Reputation: 14

Suppose u want to make 'Dim' to Blue color as VS:-

Paste this:

If RichTextBox1.Text.EndsWith("Dim") Then
        RichTextBox1.Select(RichTextBox1.TextLength - 3, 3)
        RichTextBox1.SelectionColor = Color.Blue
        RichTextBox1.Select(RichTextBox1.TextLength, RichTextBox1.TextLength)
        RichTextBox1.SelectionColor = Color.Black
    End If

Add this code to RichTextBox to Text_Changed.

Upvotes: 0

Abdusalam Ben Haj
Abdusalam Ben Haj

Reputation: 5423

Try this :

Dim wordslist As New List(Of String)
wordslist.Add("Hello")
wordslist.Add("World")

Dim len As Integer = RichTextBox1.TextLength

For Each word As String In wordslist

    Dim lastindex = RichTextBox1.Text.LastIndexOf(word)
    Dim index As Integer = 0

    While index < lastindex

    RichTextBox1.Find(word, index, len, RichTextBoxFinds.None)
    RichTextBox1.SelectionColor = Color.Blue
    index = RichTextBox1.Text.IndexOf(word, index) + 1

    End While

Next

Modified and translated from C# from Here

Upvotes: 1

SubtleStu
SubtleStu

Reputation: 158

You need to select the text which will have a colour change.

RichTextBox1.Select(RichTextBox1.Text.IndexOf("example"),4)
 RichTextBox1.SelectionColor = Color.Red

Would render the ".com" in red or

RichTextBox1.Select(6,4)
  RichTextBox1.SelectionColor = Color.Red

Would do the same

Upvotes: 0

Related Questions