The following code aims to maintain a text buffer in a ReadOnly RichTextBox, with a maximum number of characters stored, and always kept scrolled to the bottom. It streams a realtime log.
But in my attempt to maintain the maximum character count, rtMessages.TextLength() isn't changing after rtMessages.SelectedText = String.Empty and consequently, without the defensive If block, I'd end up with an infinite loop attempting to repeatedly delete the first line of the buffer.
When I remove the ReadOnly-ness of the RichTextBox, this functionality succeeds. Seems a little strange, since AppendText succeeds, but I understand that selection is a different beast.
Can I make it so that a ReadOnly RichTextBox is programmatically modifiable?
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
                While trying to replace SelectedText in a ReadOnly RichTextBox doesn't work, using the SelectedRtf does work:
  'rtMessages.Select()
  'rtMessages.SelectionStart = 0
  'rtMessages.SelectionLength = i
  'rtMessages.SelectedText = String.Empty
  'rtMessages.SelectionLength = 0
  rtMessages.Select(0, i)
  rtMessages.SelectedRtf = "{\rtf1\ansi}"
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With