以下代码旨在在ReadOnly
RichTextBox 中维护一个文本缓冲区,其中存储了最大数量的字符,并且始终保持滚动到底部。它流式传输实时日志。
但是在我试图保持最大字符数的过程中,rtMessages.TextLength()
之后并没有改变rtMessages.SelectedText = String.Empty
,因此,如果没有防御If
块,我最终会出现一个无限循环,试图重复删除缓冲区的第一行。
当我删除ReadOnly
-ness 时RichTextBox
,此功能成功。似乎有点奇怪,既然AppendText
成功了,但我明白选择是另一种野兽。
我可以让它以ReadOnly
RichTextBox
编程方式修改吗?
Private Sub onNewData(ByRef data As String) Handles _server.clientSentData
' Add new text
rtMessages.SelectionStart = rtMessages.TextLength()
rtMessages.AppendText(data)
' Delete oldest text line-by-line until the whole buffer is shorter than MAX_TEXT_LENGTH characters
Const MAX_TEXT_LENGTH = 200
Dim textLength = rtMessages.TextLength()
While textLength > MAX_TEXT_LENGTH
Dim i As Int16 = 0
Do While rtMessages.GetLineFromCharIndex(i) < 1
i += 1
Loop
rtMessages.Select()
rtMessages.SelectionStart = 0
rtMessages.SelectionLength = i
rtMessages.SelectedText = String.Empty
rtMessages.SelectionLength = 0
If rtMessages.TextLength() = textLength Then
rtMessages.Clear()
rtMessages.AppendText("[buffer trimming algorithm failed]")
Exit While
End If
textLength = rtMessages.TextLength()
End While
' Scroll down
rtMessages.SelectionStart = rtMessages.TextLength()
rtMessages.ScrollToCaret()
End Sub