Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for custom control painting in Winforms?

Normally when I override the OnPaint method, I create pens and brushes, etc inside it and then dispose them.

I also read somewhere that instead of recreating these pens and brushes, etc to create them once as static members, and then dispose them once when the form is closed, etc.

Is this a better practice?

Is there a better way for this?

I can assume that since OnPaint is called 1000s (?) of times, that would create a lot of work for the GC compared to creating them only once.

like image 392
Joan Venge Avatar asked Nov 11 '09 21:11

Joan Venge


2 Answers

If the brushes and pens don't change, it's certainly better to create them once and reuse them. Note, however, that if your control might be used on multiple threads (which is very unlikely), you should either make them ThreadStatic (and initialize on first use per thread) or make them instance members (and dispose them in your control's Dispose override); otherwise, you'll get unreproducable GDI+ errors, as GDI+ objects cannot be used on multiple threads at once. The same is true for images.

If the they do change (for example, if you use gradient brushes which depend on the control's size), you might still want to store them in instance fields, and recreate them when the control's size (or whatever) changes.

Note, by the way, that if you use normal colors, you can use the static Brushes and Pens classes, which contain static brushes and pens for all of .Net's built-in colors, and SystemBrushes and SystemPens for system colors.

like image 120
SLaks Avatar answered Oct 02 '22 03:10

SLaks


I read an interesting article last month which suggested doing all of your painting onto a separate BufferedGraphics object, and have the on_paint method do a straight copy from that to your control's graphics object.

That way, the on-paint is faster, and you only update your BufferedGraphics when something significant changes (i.e. a line moves or text changes).

like image 39
Jonathan Avatar answered Oct 02 '22 03:10

Jonathan