Kristian
Kristian

Reputation: 1388

C# textbox stop flickering

I have a multiline textbox where I display app log. If the length is > than 1k characters, I substr the log. The problem is that it's flickering. I use timer control to update textbox with condition if data differs.

Any way around this? or is there a better way to show log? Thanks!

// this is inside timer
if(txt_log.Text != MY_LOG_VAR){
   txt_log.Text = MY_LOG_VAR;
}

// function to update log
public void Log(string data){

  MY_LOG_VAR = data + "\r\n" + MY_LOG_VAR;

  if(MY_LOG_VAR.Length > 1000){
     substr...
  }
} 

The Log function could be called even 20 times a second, the timer interval is set to 100 seconds;

it doesn't flicker much, but if a lot of data is submitted to the log it does, I need a solution that would allow the textbox to be even full screen and not flicker.. Thanks!

Upvotes: 1

Views: 2523

Answers (3)

Steve
Steve

Reputation: 216342

You should try to use TextBox.AppendText instead of replacing the entire content of your textbox.

// function to update log 
public void Log(string data)
{ 
  textBox1.AppendText(data + "\r\n");
  MY_LOG_VAR = data + "\r\n" + MY_LOG_VAR; 

}  

This is not the same as putting the new text in front of the previous one, but I think that should stop the flicker. I have done some test with a RichTextBox and there is no flicker at all (exactly as Hans Passant said in its answer)...

For example, scrolling without flickering

 richTextBox1.AppendText(data +"\n");
 richTextBox1.SelectionStart = richTextBox1.GetFirstCharIndexFromLine(richTextBox1.Lines.Count()-1);
 richTextBox1.ScrollToCaret();

Upvotes: 1

Dvlpr2878
Dvlpr2878

Reputation: 117

Have you tried surrounding your update with calls to BeginUpdate/EndUpdate on the textbox?

Upvotes: 0

Hans Passant
Hans Passant

Reputation: 942257

There isn't anything you can do about the way TextBox paints. It commits a few sins, like painting without WM_PAINT, that mattered a great deal back in 1985 when it had to run on severely constrained hardware. 1K chars is rather at the low end, 64K is a nice round number that will reduce the flicker. And be sure to use AppendText in between.

Beyond that, do consider RichTextBox instead. It double-buffers and has a better way to make the text read-only.

Upvotes: 2

Related Questions