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

后端 未结 1 1875
眼角桃花
眼角桃花 2021-01-27 07:28

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.

Bu

相关标签:
1条回答
  • 2021-01-27 07:57

    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));
    }
    
    0 讨论(0)
提交回复
热议问题