c# – Word Document.SelectionChange事件不会触发
作者:互联网
以下是基于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
解决方法:
为什么不用
Globals.ThisAddIn.Application.WindowSelectionChange +=
new ApplicationEvents4_WindowSelectionChangeEventHandler(Application_WindowSelectionChange);
而不是将Microsoft.Office.Interop.Word.Document对象转换为Microsoft.Office.Tools.Word.Document
标签:c,ms-word,vsto,office-interop 来源: https://codeday.me/bug/20190620/1244534.html