使用 IMessageFilter 时出现 ObjectDisposedException

ObjectDisposedException when using IMessageFilter

我最近遇到了一种情况,我有一个要拦截和处理消息的表单。第一次打开表单时一切正常,但关闭并再次打开后,我会收到 ObjectDisposedException。

我终于想通了,我需要打电话给

Application.RemoveMessageFilter(this)

关闭表单时,否则,它会一直尝试处理已关闭表单的消息。我在这里没有看到任何 questions/answers 解决这个问题,所以我想添加它以防其他人遇到同样的问题。

此外,MSDN 上的示例也没有显示删除邮件过滤器。

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

    public bool PreFilterMessage(ref Message m)
    {

    }
}

一定要打电话

Application.RemoveMessageFilter(this)

处理完消息后(即关闭表单时)