Override OnPaint vs Handle Paint event

  • Thread starter Thread starter sanjusunny
  • Start date Start date
S

sanjusunny

I am creating a set of User Controls with a lot of custom painting. Is
there a performance hit in doing the painting by handling the Paint
event versus putting the painting code in an overridden OnPaint method?
I will be creating a a few thousand instances of the custom control.
 
Yes, there definitely is. It is the OnPaint method that does the painting.
The Paint event is an event raised by this method. So, you already have
additional indirection going on there. In fact, since the OnPaint method is
protected, it is clearly the intent that the Paint event (and other events)
be used by other classes, rather than the one doing the painting. Events are
notifications, and they involve the creation of delegate instances and the
Message Pump. If you override OnPaint, no delegate instances must be
assigned.

To put it more simply, consider the following:

protected virtual void OnPaint(PaintEventArgs e)
{
// Paint the control
// ...
// Raise the Paint event.
if (Paint != null)
Paint(this, e);
}

If you override the above, you do not need to assign a delegate to handle
the event, and the second line of code illustrated (raising the event, or
executing the delegates assigned to it) is not executed.

--
HTH,

Kevin Spencer
Microsoft MVP
Digital Carpenter

A man, a plan, a canal,
a palindrome that has gone to s**t.
 
Hi,

I'd suggest to override the OnPaint method. The event is meant to be used
from outside code that can contribute to the control's own visual. As long
as your control doesn't just contribute, but rather this is its own face it
is naturally the painting to be done in the OnPaint override. Further more
you can decide not to fire the Paint event at all, even though I don't see a
reason why you should do this.

As far as it goes to performance hit, I don't think this should be of any
concerns.
 
Back
Top