The C# team posts answers to common questions and describes new language features
In the unmanaged world, it was quite common to intercept Win32 messages as they were plucked off the message queue. In that rare case in which you wish to do so from a managed Windows Forms application, your first step is to build a helper class which implements the IMessageFilter interface. The sole method, PreFilterMessage(), allows you to get at the underlying message ID, as well as the raw WPARAM and LPARAM data. By way of a simple example:
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);
At this point you must register your helper class with the Application type:
public class mainForm : System.Windows.Forms.Form
private MyMessageFilter msgFliter = new MyMessageFilter();
// Register message filter.
At this point, your custom filter will be automatically consulted before the message makes its way to the registered event hander. Removing the filter can be accomplished using the (aptly named) static Application.RemoveMessageFilter() method.
Tip from Andrew Troelsen
Posted by: Duncan Mackenzie, MSDN
This post applies to Visual C# .NET 2002/2003
PingBack from http://www.hilpers-esp.com/651589-peekmessage-en-net
PingBack from http://paidsurveyshub.info/story.php?title=c-frequently-asked-questions-preprocess-win32-messages-through
I tried your code but it complains that it can't find the "main"... I tried adding a main and then gives another error "object reference is required..." So, it doesn't work.
Your blog does not indicate if this filter is applied to just this form, or if it is possible to filter for all windows applications which receive the event (which you may want to filter too)