Outlook 功能区 XML - 在打开其他电子邮件项目时获取活动邮件项目

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

在所有情况下检索当前活动邮件项的最佳方法是什么。所以新邮件、当前邮件、内联回复和正常回复。 我当前的代码工作正常,直到用户在不同的屏幕上打开了一封电子邮件。这被认为是活动项目。

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;

解决方案:使用 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;
    }

使用Application.ActiveWindow属性。然后您可以检查它是 Explorer 还是 Inspector 并采取相应措施。

如果这是从功能区按钮上下文调用的,您确实需要使用 RibbonControl.ContextRibbonControl 作为参数传递给您的事件处理程序)。