redDragonzz
redDragonzz

Reputation: 1571

Prevent Bubbling of Event C#

Suppose I have an event KeyPress subscribed to by various classes. Assume that Class A also subscribes to KeyPress on the form and Class B also subscribes to KeyPress

Now I wish that only one of these classes should handle the event fired by the Form in runtime. That is let's say Class A handles first, I have tried using e.Handled = true but that is not helping in this case.

I do not want class B to handle the event fired from the form if class A has handled already, I have a work around currently which involves setting some public flags within A and B, but that is not a good idea from software engineering principle, I want the classes to be as independent of each other as possible but at the same time, should know that an event has already been handled and does not need to be handled again.

Is that possible?

Yes it's possible, need to check for e.Handled == true and .NET takes care of the rest :-)

Upvotes: 13

Views: 11244

Answers (1)

Kelly Summerlin
Kelly Summerlin

Reputation: 661

You have to check e.Handled inside each event handler like this Gist example I created.

Basically each handler needs to check for e.Handled == true and return if already handled. The Handled property does not short-circuit the event handling, it only pushes down the arguments to each subscribed event.

In my example, the Form1 class always handles the event first because it is wired up in the Form1 constructor. Thus by setting e.Handled = true in that event and then checking e.Handled == true in the other events, I can just return immediately when e.Handled == true.

Upvotes: 12

Related Questions