简体   繁体   中英

Detect mouse over User Control and all children - C# WinForms

I designed a user control with several controls inside. I drag and drop my user control on my form, then I set a mouse hover event for it to show a comment somewhere.

But there is a problem, the user should hover the mouse on the UserControl Container to see that comment, If He hovers the mouse on one of the controls inside the UserControl nothing will happen.

How to set mouse hover (or other events) to be raised on the UserControl and All of its children?

All child controls receive mouse events separately. As an option you can subscribe for the desired mouse event for all controls and raise the desired one for your user control.

For example, in the following code, I've raised the container Click , DoubleClick , MouseClick , MouseDoubleClick and MouseHover event, when the corresponding event happens for any of the children in controls hierarchy:

public UserControl1() {
    InitializeComponent();
    WireMouseEvents(this);
}
void WireMouseEvents(Control container) {
    foreach (Control c in container.Controls) {
        c.Click += (s, e) => OnClick(e);
        c.DoubleClick += (s, e) => OnDoubleClick(e);
        c.MouseHover += (s, e) => OnMouseHover(e);

        c.MouseClick += (s, e) => {
            var p = PointToThis((Control)s, e.Location);
            OnMouseClick(new MouseEventArgs(e.Button, e.Clicks, p.X, p.Y, e.Delta));
        };
        c.MouseDoubleClick += (s, e) => {
            var p = PointToThis((Control)s, e.Location);
            OnMouseDoubleClick(new MouseEventArgs(e.Button, e.Clicks, p.X, p.Y, e.Delta));
        };

        WireMouseEvents(c);
    };
}

Point PointToThis(Control c, Point p) {
    return PointToClient(c.PointToScreen(p));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM