How to Filter Window Message in .NET

Message Filter:

Message filter to prevent specific events from being raised to the control or Forms.

We can achieve the Message Filter through IMessageFilter Interface. It has overridable method name PreMessageFilter.Using this method we can customize our Message Filters.

Example : Filter/Restrict left mouse button down message

public class MyMsgFilter : IMessageFilter
{
public bool PreFilterMessage(ref Message m)
{
// Filter/Restrict left mouse button down message.
if (m.Msg == 513)
{
return true;
}
return false;
}
}

In order to monitor the Message Filter in our application you must register Filter class in your application.

public class mainForm : System.Windows.Forms.Form
{
private MyMsgFilter msgFilter = new MyMsgFilter();
public mainForm()
{
// Add message filter.
Application.AddMessageFilter(msgFilter);
}
}

Following way you can remove your Message Filter
Application.RemoveMessageFilter(msgFilter);

No comments: