【问题标题】:Word Document.SelectionChange event does not fireWord Document.SelectionChange 事件不会触发
【发布时间】:2013-04-11 16:33:35
【问题描述】:

以下是我的代码(为便于阅读而简化的版本)来自基于 VSTO 的 Word 插件。

问题是,如果我打开了两个文档,例如文档和一个模板,我的插件会帮助开发模板并且工作正常,直到模板关闭并在同一个 Word 实例中重新打开(文档文件保留 Word活)。一旦发生这种情况,即使附加了侦听器(通过调试器确认),也不会收到 SelectionChange 事件。

这段代码有什么问题吗?还有其他方法可以附加选择更改事件吗?

void Application_DocumentOpen(Word.Document Doc)
{
   // this method gets called as intended
   Document vstoDoc = Globals.Factory.GetVstoObject(doc);
   vstoDoc.SelectionChange += new Microsoft.Office.Tools.Word.SelectionEventHandler(ThisDocument_SelectionChange);
}

private void Application_DocumentBeforeClose(Word.Document doc, ref bool Cancel)
{
   // this one also gets called as intended
    Document vstoDoc = Globals.Factory.GetVstoObject(doc);
    vstoDoc.SelectionChange -= new Microsoft.Office.Tools.Word.SelectionEventHandler(ThisDocument_SelectionChange);

}

void ThisDocument_SelectionChange(object sender, SelectionEventArgs e)
{  
    // this doesn't get called if the document is closed and open again within the same Word instance
    Log("Selection changed");
}    

更新:这似乎是 VSTO 错误。

附加到其他事件可以正常工作,我可以使用 ContentControlOnEnter/Exit:

vstoDoc.SelectionChange += ThisDocument_SelectionChange; // doesn't work
vstoDoc.ContentControlOnEnter += vstoDoc_ContentControlOnEnter; // works
vstoDoc.ContentControlOnExit += vstoDoc_ContentControlOnExit;   // works

【问题讨论】:

  • 尝试“WindowSelectionChange”。在这里面,您可能还需要将 ActiveDocument 设置为选择的活动文档,即 selection.Application.ActiveDocument。这会解决打开两个文档的问题吗?

标签: c# ms-word vsto office-interop


【解决方案1】:

你为什么不使用

Globals.ThisAddIn.Application.WindowSelectionChange +=
                new ApplicationEvents4_WindowSelectionChangeEventHandler(Application_WindowSelectionChange);

而不是将您的 Microsoft.Office.Interop.Word.Document 对象转换为 Microsoft.Office.Tools.Word.Document

【讨论】:

  • 这行得通,谢谢!我已经解决了这个问题,因为我只对内容控制选择感兴趣,但这仍然回答了我原来的问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-09-18
  • 2015-06-25
  • 2014-11-30
  • 2012-06-12
  • 1970-01-01
  • 2014-09-13
  • 1970-01-01
相关资源
最近更新 更多