mausinc
mausinc

Reputation: 537

Outlook Ribbon XML - Get Active MailItem when other email item is open

What's the best way to retrieve the current active mailitem for all situations. So new mail, current mail, inline reply and normal reply. My current code works ok until user has an email open in different screen. This is considered to be the active item.

MailItem mailItem = null;

      Inspector inspector = Globals.ThisAddIn.Application.ActiveInspector();
      if(inspector != null)
      {

        object item = inspector.CurrentItem;
        if(item is MailItem)
        {
          mailItem = item as MailItem;
        }
        Marshal.ReleaseComObject(inspector);
        inspector = null;
      }
      else
      {
        Explorer explorer = Globals.ThisAddIn.Application.ActiveExplorer();
        try
        {
          mailItem = explorer.GetType().InvokeMember("ActiveInlineResponse", BindingFlags.GetProperty
                                                                             | BindingFlags.Instance |
                                                                             BindingFlags.Public, null, explorer, null)
            as MailItem;
        }
        catch(Exception) { }

        if(mailItem == null)
        {
          if(explorer.Selection.Count > 0)
          {
            mailItem = Globals.ThisAddIn.Application.ActiveExplorer().Selection[1];
          }
        }
        Marshal.ReleaseComObject(explorer);
        explorer = null;
      }
      return mailItem;

Solution : Use the IRibbonControl

internal static MailItem GetMailItem(IRibbonControl control)
    {
      // Check to see if an item is selected in explorer or we are in inspector.
      if(control.Context is Inspector)
      {
        Inspector inspector = (Inspector)control.Context;

        if(inspector.CurrentItem is MailItem)
        {
          return inspector.CurrentItem as MailItem;
        }
      }

      if(control.Context is Explorer)
      {
        Explorer explorer = (Explorer)control.Context;

        Selection selectedItems = explorer.Selection;
        if(selectedItems.Count != 1)
        {
          return null;
        }

        if(selectedItems[1] is MailItem)
        {
          return selectedItems[1] as MailItem;
        }
      }

      return null;
    }

Upvotes: 2

Views: 972

Answers (1)

Dmitry Streblechenko
Dmitry Streblechenko

Reputation: 66225

Use Application.ActiveWindow property. You can then check if it is an Explorer or an Inspector and act accordingly.

If this is called from a ribbon button context, you really need to use RibbonControl.Context (RibbonControl is passed as a parameter to your event handler).

Upvotes: 4

Related Questions