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