从C#WinForm的每一个组件捕获鼠标事件 [英] Capturing Mouse Events from every component on C# WInForm

查看:1547
本文介绍了从C#WinForm的每一个组件捕获鼠标事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我的WinForm C#应用程序MouseEvents一个问题。
我想在我的应用程序的所有鼠标的点击,但我不希望把一个监听器在每个子组件既不使用Windows鼠标钩子。

I have a problem with MouseEvents on my WinForm C# application. 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.

在闪光,我可以把舞台上的监听器,以获得有关电影的一切MouseEvents。
是否有C#这样的事情?一个全球性的MouseListener?

On Flash I could put a listener on Stage to get all the MouseEvents on the movie. Is there such thing on C#? A global MouseListener?


编辑:
我从IMessageFilter ANS使用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;
	}
}

,并把这个code在需要倾听全球点击控件:

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.

海贼王复杂性,这种方法被引入不必处理Windows消息,通过信息结构传递给你的preFilterMessage方法。这意味着,指代替传统的MouseDown,的MouseMove和MouseUp事件对WM_LBUTTONDOWN,WM_MOUSEMOVE,WM_LBUTTONUP等Win32的机制的文档。

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.

这篇关于从C#WinForm的每一个组件捕获鼠标事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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