First a warning: this is an advanced scenario, and you should not attempt to use this technique unless you’re sure you know what you’re doing. The reason for this warning is that while the technique described here is pretty simple, it’s also easy to get wrong in ways that could interfere significantly with the host application.

Problem description: you build an Office add-in that periodically makes calls back into the host object model. Sometimes the calls will fail, because the host is busy doing other things. Perhaps it is recalculating the worksheet; or (most commonly), perhaps it is showing a modal dialog and waiting for user input before it can continue.

If you don’t create any background threads in your add-in, and therefore make all OM calls on the same thread your add-in was created on, your call won’t fail, it simply won’t be invoked until the host is unblocked. Then, it will be processed in sequence. This is the normal case, and it is recommended that this is how you design your Office solutions in most scenarios – that is, without creating any new threads.

However, if you do create additional threads, and attempt to make OM calls on any of those threads, then the calls will simply fail if the host is blocked. You’ll get a COMException, typically something like this: System.Runtime.InteropServices.COMException, Exception from HRESULT: 0x800AC472.

To fix this, you could implement IMessageFilter in your add-in, and register the message filter on your additional thread. If you do this, and Excel is busy when you make a call on that thread, then COM will call back on your implementation of IMessageFilter.RetryRejectedCall. This gives you an opportunity to handle the failed call – either by retrying it, and/or by taking some other mitigating action, such as displaying a message box to tell the user to close any open dialogs if they want your operation to continue.

Note that there are 2 IMessageFilter interfaces commonly defined. One is in System.Windows.Forms – you don’t want that one. Instead, you want the one defined in objidl.h, which you’ll need to import like this:

[StructLayout(LayoutKind.Sequential, Pack = 4)]

public struct INTERFACEINFO

{

    [MarshalAs(UnmanagedType.IUnknown)]

    public object punk;

    public Guid iid;

    public ushort wMethod;

}

 

[ComImport, ComConversionLoss, InterfaceType((short)1),
Guid("00000016-0000-0000-C000-000000000046")]

public interface IMessageFilter

{

    [PreserveSig, MethodImpl(MethodImplOptions.InternalCall,
        MethodCodeType = MethodCodeType.Runtime)]

    int HandleInComingCall([In] uint dwCallType, [In] IntPtr htaskCaller,
        [In] uint dwTickCount,

        [In, MarshalAs(UnmanagedType.LPArray)] INTERFACEINFO[]
        lpInterfaceInfo);

 

    [PreserveSig, MethodImpl(MethodImplOptions.InternalCall,
        MethodCodeType = MethodCodeType.Runtime)]

    int RetryRejectedCall([In] IntPtr htaskCallee, [In] uint dwTickCount,
        [In] uint dwRejectType);

 

    [PreserveSig, MethodImpl(MethodImplOptions.InternalCall,
        MethodCodeType = MethodCodeType.Runtime)]

    int MessagePending([In] IntPtr htaskCallee, [In] uint dwTickCount,
        [In] uint dwPendingType);

}

Then, implement this interface in your ThisAddIn class. Note that IMessageFilter is also implemented on the server (that is, in Excel, in our example), and that the IMessageFilter.HandleInComingCall call is only made on the server. The other 2 methods will be called on the client (that is, our add-in, in this example). We’ll get MessagePending calls after an application has made a COM method call and a Windows message occurs before the call has returned. The important method is RetryRejectedCall. In the implementation below, we display a message box asking the user whether or not they want to retry the operation. If they say “Yes”, we return 1, otherwise -1. COM expects the following return values from this call:

·         -1: the call should be canceled. COM then returns RPC_E_CALL_REJECTED from the original method call.

·         Value >= 0 and <100: the call is to be retried immediately.

·         Value >= 100: COM will wait for this many milliseconds and then retry the call.

public partial class ThisAddIn : ExcelAddInMessageFilter.IMessageFilter

{

    #region IMessageFilter Members

 

    public uint HandleInComingCall(

        uint dwCallType, IntPtr htaskCaller, uint dwTickCount,

        INTERFACEINFO[] lpInterfaceInfo)

    {

        return 1;

    }

 

    public uint RetryRejectedCall(
        IntPtr htaskCallee, uint dwTickCount, uint dwRejectType)

    {

        int retVal = -1;

        Debug.WriteLine("RetryRejectedCall");

        if (MessageBox.Show("retry?", "Alert", MessageBoxButtons.YesNo)

            == DialogResult.Yes)

        {

            retVal = 1;

        }

        return retVal;

    }

 

    public uint MessagePending(
        IntPtr htaskCallee, uint dwTickCount, uint dwPendingType)

    {

        Debug.WriteLine("MessagePending");

        return 1;

    }

 

    #endregion

}

Finally, register your message filter with COM, using CoRegisterMessageFilter. Message filters are per-thread, so you must register the filter on the background thread that you create to make the OM call. In the example below, the add-in provides a method InvokeAsyncCallToExcel, which will be invoked from a Ribbon Button. In this method, we create a new thread and make sure this is an STA thread. In my example, the thread procedure, RegisterFilter, does the work of registering the filter – and it then sleeps for 3 seconds to give the user a chance to do something that will block – such as pop up a dialog in Excel. This is clearly just for demo purposes, so that you can see what happens when Excel blocks just before a background thread call is made. The CallExcel method makes the call on Excel’s OM.

public partial class ThisAddIn : ExcelAddInMessageFilter.IMessageFilter

{

    #region IMessageFilter Members

   

    #endregion

 

    [DllImport("ole32.dll")]

    static extern int CoRegisterMessageFilter(

        IMessageFilter lpMessageFilter,
        out IMessageFilter lplpMessageFilter);

 

    private IMessageFilter oldMessageFilter;

 

    internal void InvokeAsyncCallToExcel()

    {

        Thread t = new Thread(this.RegisterFilter);

        t.SetApartmentState(ApartmentState.STA);

        t.Start();

    }

 

    private void RegisterFilter()

    {

        CoRegisterMessageFilter(this, out oldMessageFilter);

        Thread.Sleep(3000);

        CallExcel();

    }

 

    private void CallExcel()

    {

        try

        {

            this.Application.ActiveCell.Value2 =
                DateTime.Now.ToShortTimeString();

        }

        catch (Exception ex)

        {

            Debug.WriteLine(ex.ToString());

        }

    }

}