Blaargon
Blaargon

Reputation: 88

How to remove text from textbox/label without flicker

I want to create a textbox/label to display input/output from a serial connection. This program will be running over long periods of time, and since I don't want massive memory usage, I'm periodically reducing the length of the textbox content when it reaches a maximum value. Unfortunately, I've found that using the substring method causes a flicker, as the program redraws the entire content of the textbox. Basically, what I'm looking for is the opposite of the appendtext method for textboxes. If you help me out on this one, I'll totally be your best friend.

Upvotes: 2

Views: 532

Answers (4)

Patrick Hofman
Patrick Hofman

Reputation: 157098

I would advise to use another control rather than a TextBox. The way it repaints is just bad.

You might have some luck when enabling double buffering on the control (something like here: How to prevent a Windows Forms TextBox from flickering on resize?), but I usually use a ListView for this.

Upvotes: 3

SSS
SSS

Reputation: 5403

Use Array.ConstrainedCopy to modify the Textbox.Lines property. e.g. timer updates textbox every second with the time, maximum 10 lines...

Option Strict On

Public Class Form1

  Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick

    If TextBox1.Lines.GetUpperBound(0) < 9 Then
      TextBox1.Text &= vbCrLf & Now.TimeOfDay.ToString
    Else
      Dim strNew(9) As String
      Array.ConstrainedCopy(TextBox1.Lines, 1, strNew, 0, 9)
      strNew(9) = Now.TimeOfDay.ToString
      TextBox1.Lines = strNew
    End If
  End Sub
End Class

Upvotes: 1

Icemanind
Icemanind

Reputation: 48736

You should be able to add this code to your form and have most of your flickering (if not all) disappear:

protected override CreateParams CreateParams
{
    get
    {
        CreateParams cp = base.CreateParams;
        cp.ExStyle |= 0x02000000;
        return cp;
    }
}

Basically this turns on a flag that tells Windows to double buffer your controls when they repaint them.

Upvotes: 1

Graffito
Graffito

Reputation: 1718

I found an easy solution (code in c#) on Internet, perhaps too simple to work, but try:

void UpdateTextBox(string message)
{
   myTextBox.SelectionStart = myTextBox.Text.Length;
   myTextBox.SelectedText = message;
}

Upvotes: -2

Related Questions