Capture mouse click anywhere on Form (without IMessageFilter)

后端 未结 1 1529
忘掉有多难
忘掉有多难 2020-12-11 17:35

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

相关标签:
1条回答
  • 2020-12-11 18:06

    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...
    }
    
    0 讨论(0)
提交回复
热议问题