event handlers

T

Tom Porterfield

I've been fiddling with my own inheritances of UserControl lately, and have
come to an interesting problem. What is the difference between VS generating
this code for me:
this.MouseLeave += new System.EventHandler(this.EventControl_MouseLeave);

private void Control_MouseLeave(object sender, System.EventArgs e)

{

}

And me writing this code:

In this instance you have asked the control to notify you when the mouse
leaves the control. Others may have also subscribed to that same event.
You are not going to implement the MouseLeave code but you do want to take
an action when the event occurs.
protected override void OnMouseLeave(System.EventArgs e)

{

}

In this instance you are saying that you want to handle the implementation
of the OnMouseLeave code. You are replacing the base class implementation
with your own. You may choose not to raise the MouseLeave event meaning
others who have subscribed to that event will not get notification. Or you
may simply want to make sure your handling of the mouse leaving gets
processed before others are notified of the event. In that case you would
write your code in your override of OnMouseLeave and the last thing you
might do then is call base.OnMouseLeave(e).

So you can see that with the override you have control over when/if the
base implementation gets called and whether others who have subscribed to
the event get notified. From a processing standpoint this is also a little
more efficient. With the former you are simply saying "add me to the list
of objects that you notify when the MouseLeave event occurs". The base
implementation will always be called and you don't know if you will be
notified before or after any other subscribers.
 
R

Rachel Suddeth

Also, if you override the OnMouseLeave(), and then inherit another class
from your custom control, you can change the behavior of OnMouseLeave() in
the derived class. With the default event handler, it will execute whether
derived classes want it to or not. Of course, you could always make
Control_MouseLeave() in the base to be protected virtual, but it's harder
behavior to follow, since it's non-standard.

-Rachel
 
D

David Sobey

I've been fiddling with my own inheritances of UserControl lately, and have
come to an interesting problem. What is the difference between VS generating
this code for me:
this.MouseLeave += new System.EventHandler(this.EventControl_MouseLeave);

private void Control_MouseLeave(object sender, System.EventArgs e)

{

}

And me writing this code:

protected override void OnMouseLeave(System.EventArgs e)

{

}

Cheers
Dave
 

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