[英]How to color multiple text from richtextbox in vb.net
So I made a chat in vb.net (using FTP server) and I want to color each name from my chat so the file with messages is something like the following: 因此,我在vb.net(使用FTP服务器)中进行了聊天,我想为聊天中的每个名称加上颜色,因此带有消息的文件如下所示:
#2George: HI
#2George: Hi geoo
and using RichTextBox1 textchanged
event I add: 并使用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
the first name (George) changed his color but the second one didn't. 第一个名字(乔治)改变了他的肤色,但第二个没有改变。
Any ideas why this is happening? 任何想法为什么会这样?
The main problem is that your IndexOf calculations are using the index of the current line, but you are not translating that index to where that line is being used in the RichTextBox. 主要问题是您的IndexOf计算使用的是当前行的索引,但是您没有将该索引转换为RichTextBox中该行的使用位置。 That is, your second line of #2George: Hi geoo
is finding an index of 0 for the # sign, but index 0 in the RichTextBox is referring to the line #2George: HI
, so you keep redrawing the first line every time. 也就是说, #2George: Hi geoo
第二行#2George: Hi geoo
正在为#符号找到索引0,但是RichTextBox中的索引0指向#2George: HI
,因此您每次都会重#2George: HI
第一行。
To fix the immediate problem: 要解决当前的问题:
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
The next problem is that doing this in the TextChanged event re-draws all the lines all the time. 下一个问题是,在TextChanged事件中执行此操作将始终重新绘制所有行。 That won't scale too well. 那不会很好地扩展。 Consider drawing the text before you add it to the control by using a preformatted RTF line. 请考虑先绘制文本,然后再使用预格式化的RTF行将其添加到控件中。 Something like this: 像这样:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.