在C#中的面板内的任何位置处理click事件

Sco*_*try 6 c# winforms

我的表单中有一个面板,带有一个单击事件处理程序.我还在面板内部有一些其他控件(标签,其他面板等).如果您单击面板内的任何位置,我希望单击事件进行注册.只要我没有单击面板内的任何控件,click事件就会起作用,但无论你在面板内单击什么位置,我都想触发事件.如果没有向面板内的所有控件添加相同的单击事件,这是否可行?

Han*_*ant 5

从技术上讲,这是可能的,虽然它非常难看.您需要在将消息发送到单击的控件之前捕获该消息.您可以使用IMessageFilter执行此操作,您可以在调度之前嗅探从消息队列中删除的输入消息.像这样:

using System;
using System.Drawing;
using System.Windows.Forms;

class MyPanel : Panel, IMessageFilter {
    public MyPanel() {
        Application.AddMessageFilter(this);
    }
    protected override void Dispose(bool disposing) {
        if (disposing) Application.RemoveMessageFilter(this);
        base.Dispose(disposing);
    }
    public bool PreFilterMessage(ref Message m) {
        if (m.HWnd == this.Handle) {
            if (m.Msg == 0x201) {  // Trap WM_LBUTTONDOWN
                Point pos = new Point(m.LParam.ToInt32());
                // Do something with this, return true if the control shouldn't see it
                //...
                // return true
            }
        }
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 0

您过去可以重写控件上的 OnBubbleEvent 方法。在WPF中,该机制称为路由事件:http://weblogs.asp.net/vblasberg/archive/2010/03/30/wpf-routed-events-bubbling-several-layers-up.aspx