我如何捕获鼠标移动事件 [英] How do I capture the mouse move event

查看:618
本文介绍了我如何捕获鼠标移动事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想捕捉鼠标移动事件在我的主要形式。虽然我能够连线了 MouseEventHandler 为主要形式,事件不再当光标在用户控件或任何其它控制火灾。我如何确保我总是有鼠标的位置。

I would like to capture the mouse move event in my main form. Although I am able to wire up the MouseEventHandler for the main form, the event no longer fires when the cursor is over a UserControl or any other control. How do I ensure that I always have the mouse position.

推荐答案

您可以用较低水平鼠标钩子。请参见这个的例子并为您在HookCallback的WM_MOUSEMOVE mesage。

You could use a low level mouse hook. See this example and check for the WM_MOUSEMOVE mesage in HookCallback.

您也可以使用IMessageFilter类抓老鼠事件和触发事件,以获得位置(注意:这只会在窗口的位置,而不是它之外):

You could also use the IMessageFilter class to catch the Mouse Events and trigger an event to get the position (note: this will only get the position over the window, not outside of it):

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

这篇关于我如何捕获鼠标移动事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆