【发布时间】:2015-11-07 19:04:24
【问题描述】:
我想为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
【问题讨论】:
标签: vb.net richtextbox