Create new event handler or override existing handler?

G

Guest

While developing on windows forms, I found that most forms events (e.g. Load, KeyPress, MouseMove, LostFocus, etc....) have the equivalent virtual functions in the form of OnXXXX which can be overwritten. If I want to handle the KeyPress event, is it recommended to create an event handler in the constructor,

this.KeyPress += new KeyPressEventHandler(form1_KeyPress);

or to override the OnKeyPress virtual function?

I have tested both ways and didn't find any substantial differences between them. Is there any guideline to follow on which method to use?
 
C

Claes Bergefall

Two differences that I can think of at the moment:

1. Overriding the OnXXX methods allows you to suppress the
default Windows behaviour by not calling the base class. Sometimes
this is useful. An event handler doesn't support this (unless there
is a handled property in the eventargs). (This of cource only
applies to events corresponding to Windows messages)

2. You can have more than one eventhandler for the same event
and each handler will be invoked in turn. An overridden OnXXX
will only be called once.

Also note that it is the OnXXX method in the base class that invokes
the event handlers, meaning that if you don't call it no event handlers
will be invoked.

/claes


Woon Kiat said:
While developing on windows forms, I found that most forms events (e.g.
Load, KeyPress, MouseMove, LostFocus, etc....) have the equivalent virtual
functions in the form of OnXXXX which can be overwritten. If I want to
handle the KeyPress event, is it recommended to create an event handler in
the constructor,
this.KeyPress += new KeyPressEventHandler(form1_KeyPress);

or to override the OnKeyPress virtual function?

I have tested both ways and didn't find any substantial differences
between them. Is there any guideline to follow on which method to use?
 

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