在C#面板内的任何地方处理单击事件 [英] Handling a click event anywhere inside a panel in C#

查看:172
本文介绍了在C#面板内的任何地方处理单击事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的表单中有一个带有click事件处理程序的面板。我在面板内还有其他控件(标签,其他面板等)。如果您在面板内的任何位置单击,我希望单击事件能够注册。只要我不单击面板内的任何控件,click事件就起作用,但是无论您在面板内的何处单击,我都希望触发该事件。

I have a panel in my Form with a click event handler. I also have some other controls inside the panel (label, other panels, etc.). I want the click event to register if you click anywhere inside the panel. The click event works as long as I don't click on any of the controls inside the panel but I want to fire the event no matter where you click inside the panel. Is this possible without adding the same click event to all of the controls inside the panel?

推荐答案

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

Technically it is possible, although it is very ugly. You need to catch the message before it is sent to the control that was clicked. Which you can do with IMessageFilter, you can sniff an input message that was removed from the message queue before it is dispatched. Like this:

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

这篇关于在C#面板内的任何地方处理单击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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