一尘不染

如何捕获鼠标移动事件

c#

我想以我的主要形式捕获鼠标移动事件。尽管我可以MouseEventHandler为主窗体连接,但是当光标位于UserControl或任何其他控件上时,该事件不再触发。如何确保我始终处于鼠标位置。


阅读 311

收藏
2020-05-19

共1个答案

一尘不染

您可以使用低级鼠标挂钩。请参阅示例,并在HookCallback中检查WM_MOUSEMOVE消息。

您还可以使用IMessageFilter类来捕获Mouse Events并触发一个事件以获取位置(注意:这只会在窗口上获取位置,而不是在窗口外部):

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
   }
}
2020-05-19