【发布时间】:2014-10-22 03:22:36
【问题描述】:
当文本等于某物时,我需要在富文本框中更改一个单词的颜色,例如,如果用户输入“Pink”,则文本将为粉红色,但只有单词 pink。
如何做到这一点?
【问题讨论】:
-
如果您使用的是 Winforms,您可以选择文本框文本的一部分并将更改应用于所选内容。
标签: .net vb.net text colors richtextbox
当文本等于某物时,我需要在富文本框中更改一个单词的颜色,例如,如果用户输入“Pink”,则文本将为粉红色,但只有单词 pink。
如何做到这一点?
【问题讨论】:
标签: .net vb.net text colors richtextbox
正如@Kilazur 在他/她的评论中所说,您需要选择单词并设置SelectionColor。
这是一个例子:
Dim word As String = "word"
Dim index As Integer = Me.RichTextBox1.Text.IndexOf(word)
Do While (index > -1)
Me.RichTextBox1.Select(index, word.Length)
Me.RichTextBox1.SelectionColor = Color.Pink
index = Me.RichTextBox1.Text.IndexOf(word, (index + word.Length))
Loop
【讨论】:
选择感兴趣的文字后,可以使用SelectionColor属性。
您可以随时查找文本,但 TextChanged 事件似乎是一个很好的时机(尽管如果您有很多文本可能会很慢)
Private Sub RichTextBox1_TextChanged(sender As Object, e As EventArgs) Handles RichTextBox1.TextChanged
FindWords(RichTextBox1, "Pink", Color.Pink)
End Sub
Private Sub FindWords(rtb As RichTextBox, word As String, wordColour As Color)
'store the selection before any change was made so we can set it back later
Dim selectionStartBefore As Integer = rtb.SelectionStart
Dim selectionLengthBefore As Integer = rtb.SelectionLength
Dim selection As Integer
'loop through finding any words that match
selection = rtb.Text.IndexOf(word)
Do While selection >= 0
rtb.SelectionStart = selection
rtb.SelectionLength = word.Length
rtb.SelectionColor = wordColour
selection = rtb.Text.IndexOf(word, selection + word.Length)
Loop
'put the selection back to what it was
rtb.SelectionStart = selectionStartBefore
rtb.SelectionLength = selectionLengthBefore
rtb.SelectionColor = rtb.ForeColor
End Sub
【讨论】: