views:

128

answers:

2

In other words, I have a UserControl that has, for example, a label on it. Well, when the client registers with the MouseMove event of the UserControl, it should get that event whether the mouse is over the label or somewhere else on the UserControl. What would be the best way to set this up?

C#

+2  A: 

My favourite trick to 'pass through' events in a similar way to what you're asking for is to remember that events are implemented in a similar way to a property - a wrapper around a private delegate. You can override this behaviour using add and remove: (using new to explicitly hide Control.MouseMove)

public new event EventHandler MouseMove {
    add { m_Label.MouseMove += value; }
    remove { m_Label.MouseMove -= value; }
}

Note that there may be a better way to hide/override the MouseMove event - check how it is implemented by looking at Control in reflector, and see if there's a hook you can override to get the real base MouseMove event. Of course, your event could be named whatever you want if you don't want to hide the base MouseMove event, or even do something like this:

public new event EventHandler MouseMove {
    add {
        m_Label.MouseMove += value;
        base.MouseMove +=  value;
    }
    remove {
        m_Label.MouseMove -= value;
        base.MouseMove -= value;
    }
}
thecoop
Nice example thecoop!
Paul Sasik
Awesome. Much simpler than I expected.
Daniel Straight
A: 

You need to "translate" the events from the contained controls through your UserControl...

What i mean is that you need to handle every single event in your UserControl's children and re-fire them to the client code if there are event handlers registered.

Paul Sasik