检测鼠标悬停在用户控件和所有子控件上 - C# WinForms [英] Detect mouse over User Control and all children - C# WinForms

查看:29
本文介绍了检测鼠标悬停在用户控件和所有子控件上 - 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.

但是有一个问题,用户应该将鼠标悬停在 UserControl Container 上才能看到该评论,如果他将鼠标悬停在 UserControl 内的一个控件上,则什么都不会发生.

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.

如何将鼠标悬停(或其他事件)设置为在 UserControl 及其所有子控件上引发?

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.

例如,在下面的代码中,我提升了容器ClickDoubleClickMouseClickMouseDoubleClickMouseHover 事件,当相应的事件发生在控件层次结构中的任何子级时:

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));
}

这篇关于检测鼠标悬停在用户控件和所有子控件上 - C# WinForms的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆