2013-08-29 6 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

감사의, 그것은 작품입니다! –

관련 문제