Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
716 views
in Technique[技术] by (71.8m points)

c# - Capture mouse click anywhere on Form (without IMessageFilter)

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...