.net 根据条件更改文本框中的文本颜色

.net 根据条件更改文本框中的文本颜色,.net,vb.net,text,colors,richtextbox,.net,Vb.net,Text,Colors,Richtextbox,当文本等于某个值时,我需要更改富文本框中一个单词的颜色,因此,例如,如果用户输入“粉色”,则文本将为粉色,但仅为单词粉色 如何实现此目的?您可以在选择感兴趣的文本后使用SelectionColor属性 您可以随时查找文本,但TextChanged事件似乎是一个很好的时机(尽管如果您有很多文本,它可能会很慢) 正如@Kilazur在其评论中所述,您需要选择单词并设置SelectionColor 下面是一个例子: Dim word As String=“word” 作为整数的Dim索引=Me.Ric

当文本等于某个值时,我需要更改富文本框中一个单词的颜色,因此,例如,如果用户输入“粉色”,则文本将为粉色,但仅为单词粉色


如何实现此目的?

您可以在选择感兴趣的文本后使用SelectionColor属性

您可以随时查找文本,但TextChanged事件似乎是一个很好的时机(尽管如果您有很多文本,它可能会很慢)


正如@Kilazur在其评论中所述,您需要选择单词并设置
SelectionColor

下面是一个例子:

Dim word As String=“word”
作为整数的Dim索引=Me.RichTextBox1.Text.IndexOf(word)
边做边做(索引>-1)
Me.RichTextBox1.Select(索引,单词.长度)
Me.RichTextBox1.SelectionColor=Color.Pink
index=Me.RichTextBox1.Text.IndexOf(word,(index+word.Length))
环

如果您使用的是Winforms,您可以选择文本框文本的一部分并对其进行更改。您的代码将只检查一种颜色,因此如果输入更多颜色,则不会给出更好的解决方案。我的英语不好,因此不知道如何解释,所以我尝试了一下。1.您必须指定必须应用此代码的位置。2.它不会给出该问题的完整解决方案question@Sample我不是来评判你的英语的。不,我没有。如果这是问题的一部分和/或问题中所述,我会这样做。不是。2.)OPs问题的关键是如何“更改富文本框中一个单词的颜色”。我的回答说明了这一点。
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