C# Panel is flickering. When I try CreateParams, the situation is much worse

260 Views Asked by At

The title pretty much says it. I have a panel inside of my form. I have lots of Shapes in the panel that bounce off of each other. The more shapes I have the worse the flickering is. After searching on this site for awhile I added this to the constructor

    this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint 
    | ControlStyles.DoubleBuffer, true);

Then I found I should also add this

protected override CreateParams CreateParams
{
  get
  {
    CreateParams cp = base.CreateParams;
    cp.ExStyle |= 0x02000000;  // Turn on WS_EX_COMPOSITED (child control double-buffering)
    return cp;
  }
}

After I added this the screen flickered MUCH worse. It's not even fair to say it flickered. Most of the time it was just blank and every once in a while the shapes would flash briefly. My code to paint the shapes looks like this.

pnl.Refresh();
Graphics g = pnl.CreateGraphics();
for(int i = 0; i < numOfShapes; i++)
{
    Rectangle myRect = shapeList[i];
    g.FillRectangle(new SolidBrush(Color.Black), myRect);
}

edit:

I don't know why I can't get the last bit of code to look right. Sorry about that. I'm just refreshing the panel then looping through an array of rectangles and painting them to the panel

0

There are 0 best solutions below