How To Pre-Filter Windows Messages


Sometimes it can be useful to pre-filter messages sent to your program, there are essentially two steps to do this.

  1. Create your message filter object.
  2. Add the filter to your application.

Step 1: Create your message filter

To make an actual message filter you will need to inherit from the IMessageFilter interface, this is a pretty simple interface. So simple you only have one method to implement, below is the prototype:

public bool PreFilterMessage(ref Message m)

So below is
the class you will need to create:

public class MyMessageFilter : IMessageFilter
{
public bool PreFilterMessage(ref Message m)
{
// the filtering goes here
}
}

Basically all the message sent to your application will come through here, and if you detect your "special message" you can prefilter it (ie by returning true from this method) and do the processing here. E.G:

public class MyMessageFilter : IMessageFilter
{
public bool PreFilterMessage(ref Message m)
{
// 0x100 is the id for the message that is sent when a key is pressed down.
if (m.Msg == 0x100)
{
return true;
}
return false;
}
}

This class will now filter out all keydown messages. Now we need to associate an instance of this class with your application.

Step 2: Add the filter to your application

This is the real simple bit (can it get simpler you ask!).. well it takes only 1 line of code.. and no, it doesnt spread across three pages! To have the message filter working from start to finish you should place this line in the entry point of your application the Main function. And also place it before the line "Application.Run( new Form1() );" Below is the line that you need to add:

Application.AddMessageFilter( new MyMessageFilter() );

And there you have it! Try placing a MessageBox.Show("Key Pressed Down"); in the if statement block.

NOTE: I have on occasion found the odd message slipping through! If you wish to create your own message yous the static method Message.Create() - I am still working on how to send messages.