简体   繁体   English

即使在C#中单击用户控件,如何触发表单单击事件

[英]How to fire form click event even when clicking on user controls in c#

I need to detect all mouse click from a Windows forms application which has many user controls in it. 我需要从具有许多用户控件的Windows窗体应用程序中检测所有鼠标单击。 I can capture every controls click event and pass it to main form but this would not be practicle because form has many custom user controls (over a hundred) and some of the are already using this event. 我可以捕获每个控件的click事件并将其传递给主表单,但这不是实用的做法,因为表单具有许多自定义用户控件(超过一百个),并且某些控件已经在使用此事件。 I tried to add click, mouseclick, mouse up and down events but I couldn't make them fire if you click on the user controls instead of an empty part of the form. 我试图添加click,mouseclick,mouse up和down事件,但是如果您单击用户控件而不是表单的空白部分,则无法触发它们。 I searched the net for possible solutions but nothing was satisifactory. 我在网上搜索了可能的解决方案,但没有令人满意的结果。

Is there a practicle way to make the form click event fire even clicking on the user controls? 有没有一种实用的方法可以使表单单击事件即使在用户控件上单击也可以触发? I also wellcome any suggestions to record user mouse clicks without using form click event. 我也欢迎在不使用表单点击事件的情况下记录用户鼠标点击的任何建议。

    [System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
    protected override void WndProc(ref Message m)
    {
        // 0x210 is WM_PARENTNOTIFY
        // 513 is WM_LBUTTONCLICK
        if (m.Msg == 0x210 && m.WParam.ToInt32() == 513)
        {
            // get the clicked position
            var x = (int)(m.LParam.ToInt32() & 0xFFFF);
            var y = (int)(m.LParam.ToInt32() >> 16);

            // get the clicked control
            var childControl = this.GetChildAtPoint(new Point(x, y));

            // call onClick (which fires Click event)
            OnClick(EventArgs.Empty)

            // do something else...
        }
        base.WndProc(ref m);
    }

This question is quite old now, but there are solutions that don't involve overriding the WndProc of the form. 这个问题现在已经很老了,但是有些解决方案并不涉及重写表格的WndProc。

For example, you can recursively add a click event to all controls in the control hierarchy using something like this: 例如,您可以使用以下方式将click事件递归添加到控件层次结构中的所有控件:

private void SetupNestedClickEvents(Control control, EventHandler handler)
{
    control.Click += handler;
    foreach (Control ctl in control.Controls)
        SetupNestedClickEvents(ctl, handler);
}

You simply call it like this (with ctl being the Form , UserControl , or Control you want to apply this to): 您可以像这样简单地调用它( ctl是要应用到的FormUserControlControl ):

SetupNestedClickEvents(ctl, (sender, e) => { // Your code here });

For example: 例如:

SetupNestedClickEvents(this, (sender, e) => { Close(); });

Run on the current Form , will set any control in the hierarchy anywhere under the form to close the form when clicked. 在当前Form上运行,将在该窗体下的任何位置设置层次结构中的任何控件,以在单击时关闭该窗体。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM