问题
I can find a million examples of doing reg ex to apply syntax highlighting to a rich text box. but what i need it just a simple way to add in a word of a diffrent color.
What would the code be to just put the words "Hello World" into a textbox and have Hello be red and World be green?
This code doesnt work.
this.richTextBox1.SelectionColor = Color.Red
this.richTextBox1.text += "Test"
回答1:
Select the text after you put it in and then change the color.
For example:
richTextBox1.Text += "Test"
richTextBox1.Select(richTextBox1.TextLength - 4, 4)
richTextBox1.SelectionColor = Color.Red
回答2:
This code adds text "Hello" in red color and "World" in green to the RichTextBox.
RichTextBox1.SelectionColor = Color.Red
RichTextBox1.SelectedText = "Hello "
RichTextBox1.SelectionColor = Color.Green
RichTextBox1.SelectedText = "World"
回答3:
Ive worked with it in VB6 and i think its the same: You must select the text and then apply
this.richTextBox1.SelectionColor = Color.Red
The added text always appears in the defaut color, you must select it and then change its color:
this.richTextBox1.text="Hello world!"
this.richTextBox1.selstart=0
this.richTextBox1.sellength=5
this.richTextBox1.SelectionColor = Color.Red
As i dont use vb.net, you must check the spelling but i think thats the key. The code i wrote is supposed to print "Hello" in red and "World!" in black.
回答4:
Try this
RichTextBox2.SelectionLength = 0
RichTextBox1.SelectionStart = 0
' We deselect everything first in case the user has something selected.
RichTextBox1.SelectionColor = Color.Red
RichTextBox1.SelectedText = "Hello "
RichTextBox1.SelectionColor = Color.Green
RichTextBox1.SelectedText = "World "
This will add it to the start of the textbox. I think you could also make SelectionStart = RichTextBox1.TextLength which would put it at the end instead of the start.
回答5:
The code doesn't work:
this.richTextBox1.SelectionColor = Color.Red
this.richTextBox1.text += "Test"
Change the second line to this:
this.richTextBox1.SelectionColor = Color.Red
this.richTextBox1.selectedtext = "Test"
回答6:
Try this
Sub colorWord(ByVal word As String, ByVal color As Color) ' by im4dbr0
For i As Integer = 0 To RichTextBox1.TextLength
Try
If RichTextBox1.Text.ElementAt(i).ToString = word.ElementAt(0).ToString Then
Dim found As Boolean = False
For j As Integer = 1 To word.Count - 1
If RichTextBox1.Text.ElementAt(i + j) = word.ElementAt(j) Then
found = True
Else
found = False
Exit For
End If
Next
If found = True Then
RichTextBox1.Select(i, word.Length)
RichTextBox1.SelectionColor = color
End If
End If
Catch ex As Exception
Continue For
End Try
Next
For multiple words use loop
Dim Words As New List(Of String)
Words.Add("Its")
Words.Add("That")
Words.Add("Simple")
For i As Integer = 0 To Words.Count - 1
colorWord(Words.Item(i), Color.Red)
Next
来源:https://stackoverflow.com/questions/1683779/simple-text-color-in-rich-text-box