如何捕获鼠标移动事件

18

我希望在我的主窗体中捕获鼠标移动事件。虽然我能够为主窗体连接MouseEventHandler,但当光标位于用户控件或任何其他控件上时,事件不再触发。我该如何确保始终获取鼠标位置。


请按照重复的线程中所述使用IMessageFilter。 - Hans Passant
5个回答

29
你可以使用低级别的鼠标钩子。参考此示例,并在HookCallback中检查WM_MOUSEMOVE消息。
你还可以使用IMessageFilter类来捕获鼠标事件并触发事件以获取位置(请注意:这将仅获取窗口内的位置,而不是窗口外的位置):
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace GlobalMouseEvents
{
   public partial class Form1 : Form
   {
      public Form1()
      {
         GlobalMouseHandler gmh = new GlobalMouseHandler();
         gmh.TheMouseMoved += new MouseMovedEvent(gmh_TheMouseMoved);
         Application.AddMessageFilter(gmh);

         InitializeComponent();
      }

      void gmh_TheMouseMoved()
      {
         Point cur_pos = System.Windows.Forms.Cursor.Position;
         System.Console.WriteLine(cur_pos);
      }
   }

   public delegate void MouseMovedEvent();

   public class GlobalMouseHandler : IMessageFilter
   {
      private const int WM_MOUSEMOVE = 0x0200;

      public event MouseMovedEvent TheMouseMoved;

      #region IMessageFilter Members

      public bool PreFilterMessage(ref Message m)
      {
         if (m.Msg == WM_MOUSEMOVE)
         {
            if (TheMouseMoved != null)
            {
               TheMouseMoved();
            }
         }
         // Always allow message to continue to the next filter control
         return false;
      }

      #endregion
   }
}

3
这很好用,谢谢。我使用了你在这里发布的源代码。不过我注意到,即使鼠标没有移动,MouseMoved函数也会被连续调用。当鼠标不在应用程序上方时,它会停止触发。 - Randy Gamage
1
@SwDevMan81 人们是如何找到消息ID的十六进制代码的查找位置的呢?我看到所有这些导入调用与User32 dll调用,并且真的想知道在哪里可以找到有关此信息的信息。 - Dbl
2
@AndreasMüller - 键盘通知鼠标通知 - SwDevMan81
1
@SwDevMan81 就像 Randy 所说的那样,即使鼠标没有移动,它仍然不断地调用函数,我测试了一下,出了什么问题? - Shift 'n Tab
在我的简单应用程序中,只有当鼠标在窗口内移动时才起作用,也许需要更高的权限才能从其他进程中捕获鼠标事件?Win10 x64 - René W.
@RandyGamage 在 gmh_TheMouseMoved() 函数中,您可以将一个变量设置为鼠标的最后位置,然后检查鼠标自上次以来是否实际移动。如果没有移动,则不执行任何操作。 - DCOPTimDowd

10

这里是解决方案。虽然我看到另一个答案采用了类似的方法,但因为我写了这个答案,所以我想发布它。在这里,MouseMessageFilter有一个名为MouseMove的静态事件,你可以从应用程序中的任何地方订阅它。

static class Program
{
    [STAThread]
    static void Main() {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);            
        Application.AddMessageFilter(new MouseMessageFilter());
        MouseMessageFilter.MouseMove += new MouseEventHandler(OnGlobalMouseMove);

        Application.Run(new MainForm());
    }

    static void OnGlobalMouseMove(object sender, MouseEventArgs e) {
        Console.WriteLine(e.Location.ToString());
    }
 }

class MouseMessageFilter : IMessageFilter
{
    public static event MouseEventHandler MouseMove = delegate { }; 
    const int WM_MOUSEMOVE = 0x0200;

    public bool PreFilterMessage(ref Message m) {

        if (m.Msg == WM_MOUSEMOVE) {

            Point mousePosition = Control.MousePosition;

            MouseMove(null, new MouseEventArgs(
                MouseButtons.None, 0, mousePosition.X, mousePosition.Y,0));
        }    
        return false;
    }
}

只有当 wm_mousemove 发送到您的应用程序时(即当其窗口处于活动状态或在光标下方时),此选项才有效。如果只有单个表单感兴趣,那么您需要检查该表单是否处于活动状态。另外,它也会在其他窗口处于活动状态时触发。而且,在应用程序运行之前,您无需添加过滤器。 - TakeMeAsAGuest

2
我尝试了@SwDevMan81提供的上述解决方案。虽然它很好用,但我也遇到了@Randy Gamage提到的问题:“即使鼠标没有移动,MouseMoved函数也会不断被调用。当鼠标不在应用程序上时,它会停止触发”。 无论如何,这就是我想出来的解决方案:
在窗体构造函数中:
GlobalMouseHandler.MouseMovedEvent += GlobalMouseHandler_MouseMovedEvent;
Application.AddMessageFilter(new GlobalMouseHandler());

InitializeComponent();

事件处理程序:
private void GlobalMouseHandler_MouseMovedEvent(object sender, MouseEventArgs e)
{
   try
   {
      //Do whatever ...
   }
   catch { }
}

以下是我的稍作修改的GlobalMouseHandler类:

public class GlobalMouseHandler : IMessageFilter
{
    private const int WM_MOUSEMOVE = 0x0200;
    private System.Drawing.Point previousMousePosition = new System.Drawing.Point();
    public static event EventHandler<MouseEventArgs> MouseMovedEvent = delegate { };

    #region IMessageFilter Members

    public bool PreFilterMessage(ref System.Windows.Forms.Message m)
    {
        if (m.Msg == WM_MOUSEMOVE)
        {
            System.Drawing.Point currentMousePoint = Control.MousePosition;
            if (previousMousePosition != currentMousePoint)
            {
                previousMousePosition = currentMousePoint;
                MouseMovedEvent(this, new MouseEventArgs(MouseButtons.None, 0, currentMousePoint.X, currentMousePoint.Y, 0));
            }
        }
        // Always allow message to continue to the next filter control
        return false;
    }

    #endregion
}

我希望有人可以使用它。

我找出了为什么方法被调用两次的原因,因为当事件第一次触发时,previousMousePosition 的值为 x=0;y=0,当程序跳转到 if(previousMousePosition != currentMousePoint) 时,它返回 true,我只需添加一个条件来检查 previousMousePosition 是否具有默认值,并在 if 语句之前退出函数。这解决了问题。 - Shift 'n Tab

2

这里是一个解决方案,可以在整个应用程序中使用全局鼠标处理程序来处理WPF。由于WPF中存在其他鼠标问题,我也使用了这个方法。

最初的回答:

using System.Windows.Interop;  

private const int WM_MOUSEMOVE = 0x0200;
public delegate void Del_MouseMovedEvent(Point mousePosition);

// Relative to this control, the mouse position will calculated
public IInputElement Elmt_MouseMovedRelativeElement = null;

// !! This is static; needs special treatment in a multithreaded application !!
public static event Del_MouseMovedEvent Evt_TheMouseMoved = null;

// your main function call
public MyMainWindows()
{
    // install the windows message filter first
    ComponentDispatcher.ThreadFilterMessage += ComponentDispatcher_ThreadFilterMessage;

    InitializeComponent();
    
    ...
}   

// filtering the windows messages
private void ComponentDispatcher_ThreadFilterMessage(ref MSG msg, ref bool handled)
{
    if(msg.message == WM_MOUSEMOVE)
    {
        this.Evt_TheMouseMoved?.Invoke(Mouse.GetPosition(this.Elmt_MouseMovedRelativeElement));
    }
}

// individual event for mouse movement
private void MyMouseMove(Point mousePoint)
{
    // called on every mouse move when event is assigned
    Console.WriteLine(mousePoint.X + " " + mousePoint.Y);
}

private void AnyFunctionDeeperInTheCode()
{
    // assign the handler to the static var of the main window
    MyMainWindows.Evt_TheMouseMoved += MyMouseMove;
    
    // set the element / control to which the mouse position should be calculated; 
    MyMainWindows.Elmt_MouseMovedRelativeElement = this;

    ...
    
    // undassign the handler from the static var of the main window
    MyMainWindows.Evt_TheMouseMoved -= MyMouseMove;
}

0
public partial class frmCaptureMouse : Form
{
    [DllImport("user32.dll")]
    static extern IntPtr SetCapture(IntPtr hWnd);

    public frmCaptureMouse()
    {
        InitializeComponent();
    }

    private void frmCaptureMouse_MouseMove(object sender, MouseEventArgs e)
    {
        try
        {
            lblCoords.Text = e.Location.X.ToString() + ", " + e.Location.Y.ToString();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    private void btnCapture_Click(object sender, EventArgs e)
    {
        try
        {
            SetCapture(this.Handle);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接