Thursday, August 26, 2004

 

Some notes on Windows message processing in DotNet

1.
通过Windows Form处理Win32消息

Origined by C# Tips Written By Andrew Troelsen
Translated by wayfarer
From http://www.cnblogs.com/wayfarer/archive/2004/10/24/55991.html

作者介绍:Andrew Troelsen是微软的C# MVP,同时是Intertech Training技术培训部的副总裁及合作者。这是我在Duncan Mackenzie的博客上看到的,感觉很有意思,所以翻译了几篇。原文可以查看:http://blogs.msdn.com/csharpfaq/category/7580.aspx

在非托管世界里,获取存储在消息队列的Win32消息时很常见的。如果你希望在托管的Windows Form应用程序中处理Win32消息,那么就显得有些凤毛麟角了。首先,你应该创建一个帮助类实现IMessageFilter接口。该接口提供一个单独的方法PreFilterMessage()方法,获得其内部的消息ID,也就是原始的WPARAM和LPARAM数据。一个简单例子:

public class MyMessageFilter : IMessageFilter
{
public bool PreFilterMessage(ref Message m)
{
// Intercept the left mouse button down message.
if (m.Msg == 513)
{
MessageBox.Show("WM_LBUTTONDOWN is: " + m.Msg);
return true;
}
return false;
}
}
此时,你必须使用Application类型注册你的帮助类:

public class mainForm : System.Windows.Forms.Form
{
private MyMessageFilter msgFliter = new MyMessageFilter();

public mainForm()
{
// Register message filter.
Application.AddMessageFilter(msgFliter);
}

}

此时,在消息获取Event Handler之前,你自定义的Filter会自动生效。要移去该Filter,可以使用Application的静态方法Application.RemoveMessageFilter() 。



<< Home

This page is powered by Blogger. Isn't yours?