如何在vb.net中为richtextbox中的多个文本着色

如何在vb.net中为richtextbox中的多个文本着色,vb.net,Vb.net,因此,我在vb.net中使用FTP服务器进行了一次聊天,我想给聊天记录中的每个名字涂上颜色 因此,包含消息的文件如下所示: #2George: HI #2George: Hi geoo 并使用RichTextBox1TextChanged事件添加: For Each line In RichTextBox1.Lines If Not line Is Nothing Then If line.ToString.Trim.Contains("#2") Then

因此,我在vb.net中使用FTP服务器进行了一次聊天,我想给聊天记录中的每个名字涂上颜色 因此,包含消息的文件如下所示:

#2George: HI
#2George: Hi geoo
并使用RichTextBox1TextChanged事件添加:

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
第一个名字乔治改变了颜色,但第二个没有


知道为什么会发生这种情况吗?

主要问题是,您的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