子控件的触发面板事件

Ami*_*aei 0 .net c# events winforms

我有一个名为 panel1 的面板。panel1 有一个“mosuseHover”事件处理程序。panel1 也有一些控件,如图片框、标签等。

当我在 panel1 上移动鼠标时,事件会正确触发,但是当鼠标光标在 panel1 控件(如pictureBox)上时,该事件不起作用。当鼠标光标位于子控件上时,如何使事件被调用。

我应该注意,我不想为每个子控件创建事件处理程序。

此致

Kin*_*ing 5

您可以像这样添加一个IMessageFilter来实现您自己global MouseHoverPanel

//This code uses some reflection so you must add using System.Reflection
public partial class Form1 : Form, IMessageFilter
{
     public Form1(){
       InitializeComponent();
       Application.AddMessageFilter(this);
     }
     public bool PreFilterMessage(ref Message m) {
        Control c = Control.FromHandle(m.HWnd)
        if (HasParent(c,panel1)){                
            if (m.Msg == 0x2a1){//WM_MOUSEHOVER = 0x2a1
                //Fire the MouseHover event via Reflection
                typeof(Panel).GetMethod("OnMouseHover", BindingFlags.NonPublic | BindingFlags.Instance)
                    .Invoke(panel1, new object[] {EventArgs.Empty});                    
            }
        }
        return false;
    }
    //This method is used to check if a child control has some control as parent 
    private bool HasParent(Control child, Control parent) {
        if (child == null) return false;
        Control p = child.Parent;
        while (p != null) {
            if (p == parent) return true;
            p = p.Parent;
        }
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

注意:上面的代码被实现为适用Panel. 如果您的面板仅包含停止在级别 1 的子控件。您可以通过使用c = Control.FromChildHandle(m.Hwnd)和检查控件的父级来稍微更改代码,c==panel1而不必使用HasParent检查子-祖先关系的方法。