本文介绍了捕获鼠标单击窗体上的任何位置(不带IMessageFilter)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当鼠标悬停在子Control上时,不会调用 MouseDown 事件。我尝试了 KeyPreview = true; ,但没有帮助(尽管对于 KeyDown -键盘单击而言确实如此)。 / p>

我正在寻找类似 KeyPreview 的东西,但是要进行鼠标事件。



我宁愿不使用 IMessageFilter 来处理WinAPI消息(如果有的话)。替代方法(也将 IMessageFilter 设置为 Application -wide。我只希望 Form -wide。)并遍历所有对象子控件每个订阅都有其缺点。

解决方案

您仍然可以使用MessageFilter并仅过滤ActiveForm:

 私有类MouseDownFilter:IMessageFilter {
公共事件EventHandler FormClicked;
private int WM_LBUTTONDOWN = 0x201;
私人表格form = null;

[DllImport( user32.dll)]
公共静态外部布尔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();
}
}
返回false;
}

受保护的无效OnFormClicked(){
if(FormClicked!= null){
FormClicked(form,EventArgs.Empty);
}
}
}

然后在您的表格中附加它:

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

void mouseFilter_FormClicked(object sender,EventArgs e){
//做某事...
}


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.

解决方案

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

这篇关于捕获鼠标单击窗体上的任何位置(不带IMessageFilter)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-09 05:54