0

I want to make an event that runs every time the mouse clicks anywhere on the form.

Currently i got it set this:

this.MouseClick += new System.Windows.Forms.MouseEventHandler(this.Form_MouseClick);

But this only works when not clicking on any other element like a panel Is there any way i can override this?

FancyLord
  • 88
  • 13
  • [Capturing Mouse Events from every component on WInForm](https://stackoverflow.com/questions/804374/capturing-mouse-events-from-every-component-on-c-sharp-winform) – Jimi Mar 19 '18 at 07:54
  • i've seen those, but didnt find the answer i was looking for, Backs helped me down here – FancyLord Mar 19 '18 at 08:30
  • I've posted that link because if you combine what is proposed in that answer with @Backs answer, you have a class that can handle this task very well. – Jimi Mar 19 '18 at 08:54

2 Answers2

5

You can listen WndProc, override method in your form class:

protected override void WndProc(ref Message m)
{
    //0x210 is WM_PARENTNOTIFY
    if (m.Msg == 0x210 && m.WParam.ToInt32() == 513) //513 is WM_LBUTTONCLICK
    {
        Console.WriteLine(m); //You have a mouseclick(left)on the underlying user control
    }
    base.WndProc(ref m);
}
Backs
  • 24,430
  • 5
  • 58
  • 85
-1

You need to dynamically traverse through all the controls in the form and add the MouseClick event handler. Please check this answer: Handling a Click for all controls on a Form

Below code adds MouseClick event handler to the first level of controls:

foreach (Control c in this.Controls)
{
   c.MouseClick += new MouseEventHandler(
     delegate(object sender, MouseEventArgs e)
     {
       // handle the click here
     });
 }

But if your controls have clild controld then you will have to recursively add the eventhandler:

void initControlsRecursive(ControlCollection coll)
 { 
    foreach (Control c in coll)  
     {  
       c.MouseClick += (sender, e) => {/* handle the click here  */});  
       initControlsRecursive(c.Controls);
     }
 }

/* ... */
initControlsRecursive(Form.Controls);
Habeeb
  • 7,601
  • 1
  • 30
  • 33