2014-08-28 89 views
1

當文本等於某些內容時,我需要更改富文本框中一個單詞的顏色,例如,如果用戶輸入「粉紅色」,文本將爲粉紅色,但僅限於粉紅色這個詞。在條件下更改文本框中的文本顏色

如何實現這一目標?

+0

如果你談論的WinForms,您可以選擇文本框的文本的一部分,並應用更改選擇。 – Kilazur 2014-08-28 10:00:21

回答

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 
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 
+0

您的代碼只會檢查一種顏色,所以如果輸入更多的顏色,它不會提供更好的解決方案。 – 2014-08-28 10:58:38

+0

我的英文不好,所以我不知道如何解釋,所以我試了一下。 1.您必須指定必須應用此代碼的位置。 2.它不會給出問題的完整解決方案 – 2014-08-28 12:13:08

+3

@範例我不是在這裏判斷你的英語。 )不,我不知道。如果這是問題的一部分,並且/或者在我提出的問題中陳述。不是。 2.)OPs問題的關鍵點是如何*「在一個富文本框中改變一個單詞的顏色」*。我的答案顯示瞭如何。 – 2014-08-28 12:41:35