ObjectDisposedException when using IMessageFilter

81 Views Asked by At

I recently had a situation where I had a form that I was intercepting and processing messages for. Everything worked fine the first time the form was opened, but after closing and opening again, I would get an ObjectDisposedException.

I finally figured out that I needed to call

Application.RemoveMessageFilter(this)

when closing the form, otherwise, it kept trying to process messages for the closed form. I didn't see any questions/answers on here that addressed this, so I wanted to add it in case someone else had the same problem.

Also, the example on MSDN do not show removing the message filter either.

public partial class Template_Editor : Form, IMessageFilter
{
    public Template_Editor(ICollection<Vendor> vendorList)
    {
        InitializeComponent();
        Application.AddMessageFilter(this);
    }

    public bool PreFilterMessage(ref Message m)
    {

    }
}
1

There are 1 best solutions below

0
RTravis3647 On BEST ANSWER

Make sure to call

Application.RemoveMessageFilter(this)

once you are done processing messages (i.e. when closing the form)