C# Frequently Asked Questions

The C# team posts answers to common questions

Preprocess Win32 Messages through Windows Forms

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);
      return true;
    }
    return false;
  }
}

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();

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

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

Published Wednesday, October 20, 2004 4:59 PM by CSharpFAQ
Filed under:

Comments

 

Geert Baeyaert said:

Extremely usefull indeed.
However, I've noticed that this doesn't work for WM_NOTIFY messages.

Can anyone explain why this is the case?
October 22, 2004 4:01 AM
 

厚重之刀 said:

Very Helpful!
November 3, 2004 4:02 AM
 

RebelGeekz said:

December 28, 2004 4:54 AM
 

FAQ C# said:

April 14, 2005 9:21 AM
 

FAQ C# said:

April 14, 2005 9:23 AM
 

FAQ C# (par Yannick Lejeune) said:

August 23, 2005 5:32 AM
 

Preprocess Win32 Messages through Windows Forms « Alan Kleymeyer’s WordPress Blog said:

September 1, 2006 10:24 AM
 

PeekMessage en .NET | hilpers said:

January 18, 2009 6:38 AM
 

C Frequently Asked Questions Preprocess Win32 Messages through | Paid Surveys said:

May 29, 2009 12:49 PM
Anonymous comments are disabled

© 2009 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Microsoft
Page view tracker