32

I added this to my form's constructor code:

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

But it still shows ugly artifacts when it loads the controls, whenever they change (the form and its components change (need updating) often).

What do I need to do differently?

Xenoprimate
  • 7,691
  • 15
  • 58
  • 95

1 Answers1

69

This only has an effect on the form itself, not the child controls. If you have a lot of them then the time they need to take turns painting themselves becomes noticeable, it leaves a rectangular hole where the control goes that doesn't get filled up until the child control gets it turn.

What you'd need to combat this is double-buffering the entire form and the controls. That's an option available since Windows XP which made the WS_EX_COMPOSITED style flag available. Paste this into your form to turn it on:

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

It doesn't speed up the painting at all, but the form snaps onto the screen after a delay. Eliminating the visible paint artifacts. Really fixing the delay requires not using controls. Which you'd do by using the OnPaint method to draw the 'controls' and making the OnMouseClick event smart about what 'control' got clicked by the user.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • WS_EX_COMPOSITED is only working on classic theme under win7/vista, not on aero theme. Anybody knows solution in this case? – KevinBui Dec 18 '11 at 17:05
  • It works like a charm (not a refernce to Windows 8 charms, but I'm hoping it does work on Windows 8, too, as well as XP, if needed). – B. Clay Shannon-B. Crow Raven Aug 21 '12 at 00:06
  • I have notice a problem with WS_EX_COMPOSITED is that the scroll bars do not draw when dragging the position bar. Anyway have a fix for this? – Martin Dec 01 '12 at 14:40
  • Also, if you place this in a MDI Parent form, it will fix all child forms as well without having to place the snippet in each form class. – Nathan Jan 04 '19 at 19:45
  • 1
    This is sooooo far beyond my pay grade I'm stunned! Thanks. I can't believe the rendering improvement - "Any sufficiently advanced technology is indistinguishable from magic"! – SteveCinq Jan 31 '19 at 08:11
  • This is amazing. Was trying to solve this for months. God Bless you ! – albusSimba Nov 16 '20 at 03:02