在条件下更改TextBox中的文本颜色

时间:2014-08-28 09:52:59

标签: .net vb.net text colors richtextbox

当文本等于某事时,我需要在富文本框中更改一个单词的颜色,例如,如果用户输入" Pink"文字是粉红色的,但只有粉红色。

如何实现这一目标?

2 个答案:

答案 0 :(得分:3)

如@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

答案 1 :(得分:0)

您可以在选择感兴趣的文本后使用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
相关问题