2013-08-29 86 views
1

所以我在vb.net中做了一個聊天(使用FTP服務器)並且我想從我的聊天 中爲每個名稱着色,所以帶有消息的文件如下所示:如何在vb.net中爲richtextbox中的多個文本着色

#2George: HI 
#2George: Hi geoo 

,並使用RichTextBox1 textchanged事件我補充一下:

For Each line In RichTextBox1.Lines 
    If Not line Is Nothing Then 
     If line.ToString.Trim.Contains("#2") Then 
      Dim s$ = line.Trim 
      RichTextBox1.Select(s.IndexOf("#") + 1, s.IndexOf(":", s.IndexOf("#")) - s.IndexOf("#") - 1) 
      MsgBox(RichTextBox1.SelectedText) 
      RichTextBox1.SelectionColor = Color.DeepSkyBlue 
     End If 
    End If 
Next 

的頭名(喬治)改變了顏色,但第二個沒有。

任何想法爲什麼會發生這種情況?

回答

0

主要問題是您的IndexOf計算使用的是當前行的索引,但是您沒有將該索引轉換爲在RichTextBox中使用該行的位置。也就是說,#2George: Hi geoo的第二行爲#號找到0的索引,但RichTextBox中的索引0指的是行#2George: HI,因此每次都會重繪第一行。

要解決眼前的問題:

For i As Integer = 0 To RichTextBox1.Lines.Count - 1 
    Dim startIndex As Integer = RichTextBox1.Text.IndexOf("#", _ 
            RichTextBox1.GetFirstCharIndexFromLine(i)) 
    If startIndex > -1 Then 
    Dim endIndex As Integer = RichTextBox1.Text.IndexOf(":", startIndex) 
    If endIndex > -1 Then 
     RichTextBox1.Select(startIndex, endIndex - startIndex) 
     RichTextBox1.SelectionColor = Color.DeepSkyBlue 
    End If 
    End If 
Next 

下一個問題是,在TextChanged事件這樣重新繪製的所有行所有的時間。這不會太好。考慮通過使用預先格式化的RTF行將其添加到控件之前繪製文本。類似這樣的:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 
    AddRTFLine("#2George", "Hi") 
    AddRTFLine("#2George", "Hi geoo") 
End Sub 

Private Sub AddRTFLine(userName As String, userMessage As String) 
    Using box As New RichTextBox 
    box.SelectionColor = Color.DeepSkyBlue 
    box.AppendText(userName) 
    box.SelectionColor = Color.Black 
    box.AppendText(": " & userMessage) 
    box.AppendText(Environment.NewLine) 
    box.SelectAll() 
    RichTextBox1.Select(RichTextBox1.TextLength, 0) 
    RichTextBox1.SelectedRtf = box.SelectedRtf 
    End Using 
End Sub 
+0

謝謝,它的工作! –

相關問題