How to avoid flicker when drawing

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I'm a C# (but not programming in general) novice, but I couldn't find any
answer to this elsewhere.

I'm trying to make a text scroll on the form. I thought this was a good
example to get started with the encapsulated GDI+ functions.

So, I essentially have a Timer that raises a Tick event every 100
milliseconds, in which the program takes care of redrawing. The code is as
follows:

private void timer1_Tick(object sender, EventArgs e)
{

System.Drawing.Graphics drw;
drw = System.Drawing.Graphics.FromHwnd(this.Handle);
lastPoint++;
drw.FillRectangle(new SolidBrush(this.BackColor), new
Rectangle(0,0,this.Width,this.Height));
drw.DrawString(text, this.Font, System.Drawing.Brushes.White, new
Point(100, lastPoint));
}

lastPoint is an int declared directly in the form class and is used to make
the text appear a bit offset.

This code appears to be working fine - except of the flicker. The text
scrolls well, but it flickers annoyingly. Is there anything I can do to
prevent this? I already thought about just using labels instead of GDI+
functions to avoid the many redrawings.
 
Try dropping this "magic" set of lines in your control constructor:

SetStyle(ControlStyles.DoubleBuffer, true);

SetStyle(ControlStyles.ResizeRedraw, true);

SetStyle(ControlStyles.AllPaintingInWmPaint, true);

SetStyle(ControlStyles.UserPaint, true);



cheers

dave
 
Also, try to avoid painting outside the OnPaint event handler. It's a bit of
a golden rule as far as i can tell. If you don't, everytime you draw your
new string, OnPaint will get called, possibly painting over what you just
did (which could explain the flicker), or all sorts of bad evil things.

cheers
dave
 
Back
Top