1
votes

Visual Studio 2015. Outlook 2016.

I want to write a plug-in that replaces certain forms of text with a hyperlink while looking at the email in either the reading pane or an Inspector.

I can subscribe to the ItemLoad event:

    private void ThisAddIn_Startup(object sender, System.EventArgs e)
    {
        this.Application.ItemLoad += new Microsoft.Office.Interop.Outlook.ApplicationEvents_11_ItemLoadEventHandler(OnItemLoad);
    }

    private void OnItemLoad(object item)
    {
        Outlook.MailItem mailItem = item as Outlook.MailItem;

        if (mailItem != null)
        {
            System.Diagnostics.Debug.WriteLine("OnItemLoad: " + mailItem.Subject);
        }
    }

But when it is fired for some reason I can't access anything on the Outlook.MailItem instance. I get the following exception:

An exception of type 'System.Runtime.InteropServices.COMException' occurred in FirstOutlookAddIn.dll but was not handled in user code

Additional information: The item’s properties and methods cannot be used inside this event procedure.

Thanks in advance!

1

1 Answers

2
votes

That error message is very unambiguous - no OOM properties or methods can be accessed in some event handlers.

One workaround would be to wait until you are out of the event handler - either use a different event (if available), or enable a timer in the OOM event handler, then in the timer event handler do what you need to do (you will be out of the OOM event handler by the time it fires). Use the Timer class from the Forms namespace as it fires on the main thread.

Keep in mind however that it is not a good idea to modify existing items - chances are the changes will persisted (also updating the last modified date) or that Outlook will prompt the user to save the changes.

Try to work with the Word editor exposed through Inspector.GetWordEditor. For the reading pane, you can use the ReadingPane object in Redemption.