Outlook VSTO how to get Custom Task Pane to work with multiple open compose windows?

103 Views Asked by At

I've followed this tutorial to create a Custome Task Pane when composing a new message: https://learn.microsoft.com/en-us/visualstudio/vsto/walkthrough-displaying-custom-task-panes-with-e-mail-messages-in-outlook?view=vs-2022&tabs=csharp

So far, it's working great. I push a button on the task pane & it fills in the BCC field on the message.

The probable is if someone opens more than one compose window, then the BCC only gets added to the most recently opened window. If I push the button on the previously opened compose window, then nothing happens.

I was doing this:

Globals.ThisAddIn.CurrentMailItem.BCC = "[email protected]";

But the CurrentMailItem is no longer correct when switching back to the first compose window.

I tried this:

foreach (Inspector inspector in Globals.ThisAddIn.inspectors)
{
    if (inspector.CurrentItem is MailItem)
    {
        MailItem mailItem = inspector.CurrentItem as MailItem;
        mailItem.BCC = "test";
    }
}

And it was able to add the BCC to both compose windows, but that's not what I want. How can I add the BCC to the current mailItlem of the clicked on task pane?

2

There are 2 best solutions below

0
Eugene Astafiev On BEST ANSWER

Only one Outlook inspector can be active, so you may call the ActiveInspector method which returns the topmost Inspector object on the desktop. Also, as Dmitry proposed, you can keep an Inspector reference in the task pane user control class and use when required.

But a better yet approach is to use the Outlook Form Regions instead of task panes in Outlook, see Create Outlook form regions for more information. In that case you can use the built-in property for that - FormRegionControl.OutlookItem which returns the Outlook item in which the form region appears.

0
Dmitry Streblechenko On

When you are creating your CTP, your work with a particular Inspector object. You can store that Inspector as a member of your CTP class.

Moreover, CustomTaskPane object implements Window property, which you can cast as Inspector or Explorer object as appropriate.