从每个组件捕获鼠标事件 [英] Capturing mouse events from every component
问题描述
我在WinForm C#应用程序上遇到MouseEvents问题.
I have a problem with MouseEvents on my WinForm C# application.
我想在我的应用程序上获得 all 的鼠标单击,但是我不想在每个子组件中都放置一个侦听器,也不使用Windows鼠标钩.
I want to get all mouse clicks on my application, but I don't want to put a listener in every child component neither use Windows mouse hook.
在Flash上,我可以在舞台上放置一个侦听器,以获取电影中的所有MouseEvent.
On Flash I could put a listener on Stage to get all the MouseEvents on the movie.
C#上有这样的东西吗?全局的MouseListener?
Is there such thing on C#? A global MouseListener?
我从IMessageFilter和使用过的Application.AddMessageFilter创建此类.
I create this class from IMessageFilter ans used Application.AddMessageFilter.
public class GlobalMouseHandler : IMessageFilter{
private const int WM_LBUTTONDOWN = 0x201;
public bool PreFilterMessage(ref Message m){
if (m.Msg == WM_LBUTTONDOWN) {
// Do stuffs
}
return false;
}
}
并将此代码放在需要监听全局点击的控件上:
And put this code on the Controls that need listen global clicks:
GlobalMouseHandler globalClick = new GlobalMouseHandler();
Application.AddMessageFilter(globalClick);
推荐答案
一种简单的方法是通过调用Application.AddMessageFilter
并编写实现IMessageFilter
接口的类来添加消息循环过滤器.
One straightforward way to do this is to add a message loop filter by calling Application.AddMessageFilter
and writing a class that implements the IMessageFilter
interface.
通过IMessageFilter.PreFilterMessage
,您的班级将看到通过应用程序的消息循环传递的所有输入消息. PreFilterMessage
还可以决定是否将这些消息传递给目的地为它们的特定控件.
Via IMessageFilter.PreFilterMessage
, your class gets to see any inputs messages that pass through your application's message loop. PreFilterMessage
also gets to decide whether to pass these messages on to the specific control to which they're destined.
此方法引入的一项复杂性是必须通过传递给您的PreFilterMessage
方法的Message结构来处理Windows消息.这意味着引用WM\_LBUTTONDOWN, WM\_MOUSEMOVE
,WM\_LBUTTONUP
等上的Win32文档,而不是常规的MouseDown
,MouseMove
和MouseUp
事件.
One piece of complexity that this approach introduces is having to deal with Windows messages, via the Message struct passed to your PreFilterMessage
method. This means referring to the Win32 documention on WM\_LBUTTONDOWN, WM\_MOUSEMOVE
, WM\_LBUTTONUP
etc, instead of the conventional MouseDown
, MouseMove
and MouseUp
events.
这篇关于从每个组件捕获鼠标事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!