2017-06-17 52 views
-1

我有一個RichTextBox(我需要找到所有對應於TextBox的單詞的文本),TextBox(用於輸入要查找的單詞)和一個Button,當我點擊按鈕,我希望在RichTextBox中,所有與TextBox中寫入的單詞相對應的單詞都用一種顏色(例如黃色)突出顯示。我知道如何找到這個詞的第一個詞,但我不知道如何找到所有的詞語。在VB.NET中高亮顯示字詞

突出顯示僅單詞的第一個匹配的代碼:

'CodeCS is my RichTextBox 

CodeCS.SelectionBackColor = Color.White 
CodeCS.Find(ToolStripTextBox1.Text, RichTextBoxFinds.MatchCase) 
CodeCS.SelectionBackColor = Color.Yellow 
+0

它如果你發佈你的解決問題的嘗試會更好。否則你的問題只是一個經典_gimme teh codez_,它不會被好評 – Steve

+0

歡迎來到堆棧溢出。如果你包含你已經編寫的代碼,那麼幫助你會容易得多。 – sapanoia

+0

@sapanoia 'CodeCS.SelectionBackColor = Color.White' 'CodeCS.Find(ToolStripTextBox1.Text,RichTextBoxFinds.MatchCase)' 'CodeCS.SelectionBackColor = Color.Yellow' 但它強調只有第一次出現這個詞並不是所有的單詞 – Renaud42

回答

1

這裏一個簡單的循環在搜索文本 (RTB是搜索的文本在RichTextBox)

Sub HighlightWord(searchText As String) 
    Dim len = searchText.Length 
    Dim pos = rtb.Find(searchText, 0, RichTextBoxFinds.NoHighlight) 
    While (pos >= 0) 
     rtb.Select(pos, len) 
     rtb.SelectionBackColor = Color.Yellow 
     if pos + len >= rtb.Text.Length Then 
      Exit While 
     End If 
     pos = rtb.Find(searchText, pos + len, RichTextBoxFinds.NoHighlight) 
    End While 
End Sub 
+0

我的代碼是在VB.NET中,而不是C#。但是,謝謝。 – Renaud42

+0

轉換爲VB.NET – Steve

+0

它的工作原理!非常感謝 ! – Renaud42