【问题标题】:In an Outlook 2013 C# VSTO project, why does the Explorer SelectionChange event fire twice在 Outlook 2013 C# VSTO 项目中,为什么 Explorer SelectionChange 事件会触发两次
【发布时间】:2015-01-12 12:21:13
【问题描述】:

在我的 Outlook 2013 C# VSTO 项目中,我注意到 Explorer SelectionChange 事件触发了两次。我认为这一定是由于我的代码中的错误(例如将事件处理程序挂钩两次),但我找不到任何此类错误。

所以我回到基础并创建了一个小的 VSTO Outlook 2013 插件测试项目,同样的事情也发生在那里。 Explorer SelectionChange 事件被触发两次。

public partial class ThisAddIn
{
    private Explorer _activeExplorer;

    private void ThisAddIn_Startup(object sender, System.EventArgs e)
    {
        _activeExplorer = Application.Explorers[1];

        _activeExplorer.SelectionChange += _activeExplorer_SelectionChange;
    }

    private void _activeExplorer_SelectionChange()
    {
        System.Diagnostics.Debug.WriteLine("_activeExplorer_SelectionChange : " + DateTime.Now.ToString());
    }

    private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
    {
    }

    #region VSTO generated code

    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InternalStartup()
    {
        this.Startup += new System.EventHandler(ThisAddIn_Startup);
        this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
    }

    #endregion
}

我可以围绕这个编写代码,但肯定不会触发两次 SelectionChange 事件。

知道为什么 SelectionChange 事件会触发两次吗? 我该怎么做才能让它只触发一次(除了编写我自己的代码来检查选择是否已更改)?

【问题讨论】:

  • 您如何确定它会触发两次?您是否确保在调试会话之间关闭 Outlook?您不会在关机期间取消订阅,因此您可能会在调试期间两次订阅同一个资源管理器实例
  • 我不认为你会得到这个问题的直接答案。它确实触发了两次(每个参与过这个事件的人都可以确认),但我怀疑你会得到一个关于原因的官方解释。 “检查选择是否已更改”解决方法是我见过的每个时间密集型 SelectionChange 事件处理程序的一部分。
  • 您打开了多少个资源管理器窗口?尝试使用 ActiveExplorer 方法而不是索引器。它有帮助吗?最后,您是否为 Outlook 安装了任何其他加载项?

标签: c# outlook vsto


【解决方案1】:

您需要关闭 Outlook 中的阅读窗格

关闭它后,您一次只能获得一个事件。

【讨论】:

  • 关闭了阅读窗格,只触发了 1 个 SelectionChange 事件。谜团已揭开。谢谢。
  • 抱歉,但这并不是问题的真正解决方案。您不能强制用户关闭阅读窗格 - 这对于 Outlook 用户来说绝对是一个舒适的功能。 :|
【解决方案2】:
private void ThisAddIn_Startup(object sender, EventArgs e){
    Application.ActiveExplorer().SelectionChange += activeExplorer_SelectionChange;
}
private void activeExplorer_SelectionChange()
{
    Selection selection = Application.ActiveExplorer().Selection;
    if (selection != null && selection.Count == 1 && selection[1] is MailItem)
    {
        MailItem selectedMail = selection[1] as MailItem;
        selectedMail.Read += SelectedMail_Read;
    }
}

private void SelectedMail_Read()
{
     Selection selection = Application.ActiveExplorer().Selection;
     MailItem selectedMail = selection[1] as MailItem;
     ...
}

【讨论】:

  • 虽然此代码可能会回答问题,但提供有关 why 和/或 如何 此代码回答问题的附加上下文可提高其长期价值.
猜你喜欢
  • 2011-09-19
  • 1970-01-01
  • 1970-01-01
  • 2014-07-31
  • 2014-10-05
  • 1970-01-01
  • 2011-07-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多