Creating a UserControl... use OnPaint method or capture Paint event?

J

jrhoads23

I have been wondering this for some time. If I create my own class
inherited from an existing class or create a user control, should I be
overriding the OnFontChanged method (or similar) or capturing the
FontChanged event. It seems they both get the same accomplished - so
what is the difference between the two? Which should I be using?
For example, lets say I create a class MyButton which inherits
System.Windows.Forms.Button. Which should I use...

Protected Overrides Sub OnPaint(ByVal e As
System.Windows.Forms.PaintEventArgs)

' my code here

MyBase.OnPaint(e)
End Sub

---OR---

Private Sub Me_Paint(ByVal sender As Object, ByVal e As
System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint
' my code here

End Sub
 
N

Nicholas Paldino [.NET/C# MVP]

I would say to override the OnPaint method. It just seems cleaner, when
thinking about other controls subclassing your control, as well as the fact
that you get your work in before any event fires.

Hope this helps.
 
H

Herfried K. Wagner [MVP]

I have been wondering this for some time. If I create my own class
inherited from an existing class or create a user control, should I be
overriding the OnFontChanged method (or similar) or capturing the
FontChanged event. It seems they both get the same accomplished - so
what is the difference between the two? Which should I be using?

To Override Or To Handle?
<URL:http://www.bobpowell.net/overrideorhandle.htm>
 
B

Benoit Vreuninckx

Nicholas said:
I would say to override the OnPaint method. It just seems cleaner, when
thinking about other controls subclassing your control, as well as the fact
that you get your work in before any event fires.

Hope this helps.

Hi,

In this example, OnPaint, you should call the base implementation first
as it does the default painting, unless you're going to draw everything
yourself. By doing that, the event handlers will get invoked before
your overriding OnPaint implementation is executed. Calling the base
after you've done your drawing, would probably erase everything (by the
base). In this case the order of execution is important, yet not fully
controllable. Most of the time, the order isn't that important.
To conclude, when subclassing you should override, it's cleaner, it's
more OO (and it's a little faster FWIW). Calling the base before or
after your overriding implementation (or not at all) depends on the
situation. The event exists (only) for external clients, which can't
override the method.

Cheers,
Benoit
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top