订阅表单中所有控件的鼠标事件

问题描述 投票:6回答:3

如何轻松捕捉表单中所有控件的“鼠标按下”事件,而无需手动订阅每个事件? (C#)类似于“KeyPreview”功能,但适用于鼠标事件。

winforms events mouse
3个回答
1
投票

解决方案1

订阅表单中每个控件的每个事件当然是最简单的方法,因为您只需使用Ramesh提供的代码。

但是,另一种技术涉及覆盖父控件上的默认Windows消息处理方法(“WndProc”) - 在这种情况下,包含所有控件的表单。这会产生副作用,当鼠标光标移动到另一个父控件中包含的控件时,您将无法检测到这种副作用。

例如,您将无法检测到鼠标光标何时位于TextBox中包含的TabControl上。这是因为TabControl将继续处理所有鼠标事件。

解决方案2

以下解决方案将克服尝试使用称为Windows钩子的技术检测鼠标光标所在的控件的所有问题。

Hooks本质上允许我们捕获鼠标和键盘事件,甚至在它们被调度到具有焦点的窗口之前。

这是一个示例:

  public enum HookType : int
  {
   WH_JOURNALRECORD = 0,
   WH_JOURNALPLAYBACK = 1,
   WH_KEYBOARD = 2,
   WH_GETMESSAGE = 3,
   WH_CALLWNDPROC = 4,
   WH_CBT = 5,
   WH_SYSMSGFILTER = 6,
   WH_MOUSE = 7,
   WH_HARDWARE = 8,
   WH_DEBUG = 9,
   WH_SHELL = 10,
   WH_FOREGROUNDIDLE = 11,
   WH_CALLWNDPROCRET = 12,
   WH_KEYBOARD_LL = 13,
   WH_MOUSE_LL = 14
  }

  [StructLayout(LayoutKind.Sequential)]
  public struct POINT
  {
   public int X;
   public int Y;
  }

  [StructLayout(LayoutKind.Sequential)]
  public struct MouseHookStruct
  {
   public POINT pt;
   public int hwnd;
   public int hitTestCode;
   public int dwExtraInfo;
  }

  [DllImport("user32.dll", SetLastError = true)]
  static extern int SetWindowsHookEx(HookType hook, HookProc callback, IntPtr hInstance, uint dwThreadId);

  [DllImport("user32.dll", SetLastError= true)]
  static extern int CallNextHookEx(int hook,  int code, IntPtr wParam, IntPtr lParam);

  [DllImport("kernel32.dll")]
  static extern int GetLastError();

  [DllImport("kernel32.dll")]
  static extern int GetCurrentThreadId();

  public delegate int HookProc(int nCode, IntPtr wParam, IntPtr lParam);
  private static int hHook;

  public Form1()
  {
   InitializeComponent();

   hHook = SetWindowsHookEx(HookType.WH_MOUSE, MouseHookProc, IntPtr.Zero, (uint)GetCurrentThreadId());
   if (hHook == 0)
    MessageBox.Show("GetLastError: " + GetLastError());
  }

  private int MouseHookProc(int code, IntPtr wParam, IntPtr lParam)
  {
   //Marshall the data from the callback.
   MouseHookStruct mouseInfo = (MouseHookStruct)Marshal.PtrToStructure(lParam, typeof(MouseHookStruct));

   if (code < 0)
   {
    return CallNextHookEx(hHook, code, wParam, lParam);
   }
   else
   {
    //Create a string variable that shows the current mouse coordinates.
    String strCaption = "x = " + mouseInfo.pt.X.ToString("d") +
     "  y = " + mouseInfo.pt.Y.ToString("d");

    //You must get the active form because it is a static function.
    Form tempForm = Form.ActiveForm;

    Control c = Control.FromHandle((IntPtr)mouseInfo.hwnd);
    if (c != null)
     label1.Text = c.Name;
    else
     label1.Text = "Control not found";

    //Set the caption of the form.
    tempForm.Text = strCaption;

    return CallNextHookEx(hHook, code, wParam, lParam);
   }
  }

2
投票

我发现这是我的目的的最佳解决方案。

创建一个派生自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;
    }
}

然后在您的主窗体中添加此项以注册消息过滤器:

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

并添加此功能,以您的形式做任何事情:

public void YourMainForm_Click(object sender, EventArgs e)
{
    // do anything here...
}

1
投票

表单中的其他控制无法监听表单的鼠标事件处理程序。因为每个控件都有自己的鼠标事件列表器。

但您可以将每个控件鼠标事件订阅到窗体鼠标事件

this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.Form1_MDown);    
this.label1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.Form1_MDown); 
this.ListBox1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.Form1_MDown);

这样,您可以为所有控件鼠标事件设置单个处理程序。

© www.soinside.com 2019 - 2024. All rights reserved.