Как раскрасить текст RichTextBox в зависимости от префикса строки?
Я хотел бы покрасить все строки внутри richtextbox. Например, если префикс определенной строки
Received:
тогда это должно быть синимSend:
тогда это должно быть краснымInfo:
тогда это должно быть зеленым
*The way I output the text in the RichTextBox is by ascending order, it means that all the newest messages will be outputted at the top of the RichTextBox, the old ones will go down.
Скриншот:
коды:
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim msg_info As String = Nothing
If RB_Info.Checked = True Then
msg_info = "Info: "
End If
If RB_Send.Checked = True Then
msg_info = "Send: "
End If
If RB_Received.Checked = True Then
msg_info = "Received: "
End If
RichTextBox1.Text = RichTextBox1.Text.Insert(0, msg_info & TextBox1.Text & ControlChars.NewLine)
End Sub
End Class
Редактировать: я пытался применить этот саб, но он меняет цвет всех элементов в ListBox
Sub HighlightPhrase(box As RichTextBox, phrase As String, color As Color)
Dim pos As Integer = box.SelectionStart
Dim s As String = box.Text
Dim ix As Integer = 0
While True
Dim jx As Integer = s.IndexOf(phrase, ix, StringComparison.CurrentCultureIgnoreCase)
If jx < 0 Then
Exit While
End If
box.SelectionStart = jx
box.SelectionLength = phrase.Length
box.SelectionColor = color
ix = jx + 1
End While
box.SelectionStart = pos
box.SelectionLength = 0
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim msg_info As String = Nothing
If RB_Info.Checked = True Then
msg_info = "Info: "
HighlightPhrase(RichTextBox1, "Info", Color.Blue)
End If
If RB_Send.Checked = True Then
msg_info = "Send: "
HighlightPhrase(RichTextBox1, "Send", Color.Green)
End If
If RB_Received.Checked = True Then
msg_info = "Received: "
HighlightPhrase(RichTextBox1, "Received", Color.Red)
End If
RichTextBox1.Text = RichTextBox1.Text.Insert(0, msg_info & TextBox1.Text & ControlChars.NewLine)
End Sub
1 ответ
Я отредактировал свое решение так, чтобы новая строка появилась в верхней части RichTextBox.
Я думаю, что мое решение уродливо, потому что в основном оно перекрашивает цвет каждой строки после добавления новой строки. Представьте, что RichTextBox содержит тысячи строк. Я думаю, что вы можете минимизировать это, сохранив ограничение на количество строк в RTB, например, 100 строк.
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim msg_info As String = Nothing
If RB_Info.Checked = True Then
msg_info = "Info: "
End If
If RB_Send.Checked = True Then
msg_info = "Send: "
End If
If RB_Received.Checked = True Then
msg_info = "Received: "
End If
RichTextBox1.Text = RichTextBox1.Text.Insert(0, msg_info & TextBox1.Text & ControlChars.NewLine)
ChangeColor()
End Sub
Private Sub ChangeColor()
Dim lines = RichTextBox1.Text.Split(vbLf)
Dim startPos As Integer, endPos As Integer = -1
Dim myColor As Color
For i = 0 To lines.Length - 2 ' minus 2 because the last one is empty string
startPos = endPos + 1
endPos = startPos + lines(i).Length
RichTextBox1.Select(startPos, endPos)
If lines(i).StartsWith("Info: ") Then myColor = Color.Red
If lines(i).StartsWith("Send: ") Then myColor = Color.Blue
If lines(i).StartsWith("Received: ") Then myColor = Color.Green
RichTextBox1.SelectionColor = myColor
Next
End Sub
End Class
Альтернативное решение с использованием ListView
Возможно, вы захотите взглянуть на элемент управления ListView. Если вы не хотите ничего писать в списке, я предлагаю вам заменить RichTextBox на ListView. После добавления ListView измените View
собственность на List
,
Public Class Form1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim msg_info As String = Nothing
Dim myColor As Color
If RB_Info.Checked = True Then
msg_info = "Info: "
myColor = Color.Green
End If
If RB_Send.Checked = True Then
msg_info = "Send: "
myColor = Color.Red
End If
If RB_Received.Checked = True Then
msg_info = "Received: "
myColor = Color.Blue
End If
Dim li = New ListViewItem()
li.ForeColor = myColor
li.Text = msg_info & TextBox1.Text
ListView1.Items.Insert(0, li)
End Sub
End Class