如何捕获鼠标移动事件 [英] How do I capture the mouse move event
问题描述
我想在我的主窗体中捕获鼠标移动事件.尽管我能够为主窗体连接 MouseEventHandler
,但是当光标位于 UserControl 或任何其他控件上时,该事件不再触发.如何确保我始终拥有鼠标位置.
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 消息.
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屋!