Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I programmatically remove text from a ReadOnly RichTextBox?

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
like image 972
Lightness Races in Orbit Avatar asked Nov 10 '12 01:11

Lightness Races in Orbit


1 Answers

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}"
like image 120
LarsTech Avatar answered Sep 30 '22 19:09

LarsTech