Application.AddMessageFilter(IMessageFilter) Method

Definition

Adds a message filter to monitor Windows messages as they are routed to their destinations.

C#
public static void AddMessageFilter(System.Windows.Forms.IMessageFilter value);
C#
public static void AddMessageFilter(System.Windows.Forms.IMessageFilter? value);

Parameters

value
IMessageFilter

The implementation of the IMessageFilter interface you want to install.

Examples

The following code example creates a message filter called TestMessageFilter. This filter blocks all messages relating to the left mouse button. Before you can use a message filter, you must provide an implementation for the IMessageFilter interface.

C#
// Creates a  message filter.
public class TestMessageFilter : IMessageFilter
{
    public bool PreFilterMessage(ref Message m)
    {
        // Blocks all the messages relating to the left mouse button.
        if (m.Msg >= 513 && m.Msg <= 515)
        {
            Console.WriteLine("Processing the messages : " + m.Msg);
            return true;
        }
        return false;
    }
}

Remarks

Use a message filter to prevent specific events from being raised or to perform special operations for an event before it is passed to an event handler. Message filters are unique to a specific thread.

To prevent a message from being dispatched, the value parameter instance that you pass to this method must override the PreFilterMessage method with the code to handle the message. The method must return false.

Caution

Adding message filters to the message pump for an application can degrade performance.

Applies to

Product Versions
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9