Search code examples
c#formsclickcontrolsmouse

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. 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. 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. 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.


Solution

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