Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subscribing to mouse events of all controls in form

How can i easily catch the "mouse down" events of all the controls in a form, without manually subscribing to each and every event? (C#) Something like the "KeyPreview" feature, but for the mouse events.

like image 449
Gal Shadeck Avatar asked Sep 03 '09 07:09

Gal Shadeck


People also ask

What are mouse events in Windows programming?

This event occurs when the mouse pointer moves while it is over a control. The handler for this event receives an argument of type MouseEventArgs. This event occurs when the mouse pointer is over the control and the user releases a mouse button. The handler for this event receives an argument of type MouseEventArgs.

What are the mouse events in VB?

VB.Net Mouse Events MouseDown – occurs when a mouse button is pressed. MouseEnter – occurs when the mouse pointer enters the control. MouseLeave – occurs when the mouse pointer leaves the control. MouseMove – occurs when the mouse pointer moves over the control.

What is mouse click event?

The MouseEvent interface represents events that occur due to the user interacting with a pointing device (such as a mouse). Common events using this interface include click , dblclick , mouseup , mousedown .


1 Answers

I found this to be the best solution for my purposes.

Create a new class derived from IMessageFilter:

public class GlobalMouseHandler : IMessageFilter
{

    private const int WM_LBUTTONDOWN = 0x201;

    public bool PreFilterMessage(ref Message m)
    {
        if (m.Msg == WM_LBUTTONDOWN)
        {
            // do something
            ((YourMainForm)Form.ActiveForm).YourMainForm_Click(null, null);
        }
        return false;
    }
}

Then in your main form add this to register the message filter:

GlobalMouseHandler globalClick = new GlobalMouseHandler();
Application.AddMessageFilter(globalClick);

And add this function to do whatever you have to, in your form:

public void YourMainForm_Click(object sender, EventArgs e)
{
    // do anything here...
}
like image 169
Joerg Aldinger Avatar answered Nov 15 '22 10:11

Joerg Aldinger