8

The MouseDown event isn't called when the mouse is over a child Control. I tried KeyPreview = true; but it doesn't help (though it does for KeyDown - keyboard clicks).

I'm looking for something like KeyPreview, but for mouse events.

I rather not use IMessageFilter and process the WinAPI message if there's a simpler. alternative (Also, IMessageFilter is set Application-wide. I want Form-wide only.) And iterating over all child Controls, subscribing each, has its own disadvantages.

ispiro
  • 26,556
  • 38
  • 136
  • 291
  • Have you look at MouseHover event ? http://msdn.microsoft.com/en-us/library/system.windows.forms.control.mousehover(v=vs.110).aspx – Bit Jan 23 '14 at 15:38
  • @downvoter Care to comment why? – ispiro Jan 23 '14 at 16:15
  • You've removed all possibilities though with your requirements. You will have to pick one of those two choices. (I'm not the down voter). – LarsTech Jan 23 '14 at 16:39
  • @LarsTech Thanks. I just assumed that since there's a simple way for keyboard keys (using `KeyPreview = true`) that there would be something similar for mouse clicks as well. – ispiro Jan 23 '14 at 16:48

1 Answers1

13

You can still use MessageFilter and just filter for the ActiveForm:

private class MouseDownFilter : IMessageFilter {
  public event EventHandler FormClicked;
  private int WM_LBUTTONDOWN = 0x201;
  private Form form = null;

  [DllImport("user32.dll")]
  public static extern bool IsChild(IntPtr hWndParent, IntPtr hWnd);

  public MouseDownFilter(Form f) {
    form = f;
  }

  public bool PreFilterMessage(ref Message m) {
    if (m.Msg == WM_LBUTTONDOWN) {
      if (Form.ActiveForm != null && Form.ActiveForm.Equals(form)) {
        OnFormClicked();
      }
    }
    return false;
  }

  protected void OnFormClicked() {
    if (FormClicked != null) {
      FormClicked(form, EventArgs.Empty);
    }
  }
}

Then in your form, attach it:

public Form1() {
  InitializeComponent();
  MouseDownFilter mouseFilter = new MouseDownFilter(this);
  mouseFilter.FormClicked += mouseFilter_FormClicked;
  Application.AddMessageFilter(mouseFilter);
}

void mouseFilter_FormClicked(object sender, EventArgs e) {
  // do something...
}
LarsTech
  • 80,625
  • 14
  • 153
  • 225