【发布时间】: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