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

时间:2017-03-30 10:13:40

标签: outlook vsto ribbon

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

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;
    }

1 个答案:

答案 0 :(得分:3)

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

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