c# - 从保存对话框中捕捉取消状态,以获取即将关闭且未保存更改的 MS Word 文档

标签 c# .net ms-word add-in

我有一个用 C# 开发的 Microsoft Word 插件。当用户尝试关闭包含未保存更改的文档时,将显示“保存”对话框。如果用户在“保存”对话框中单击“取消”,有没有办法进行捕获?

DocumentBeforeClose 事件在显示“保存”对话框之前令人恼火地触发,并且似乎没有触发封装“保存对话框”事件的事件。

为什么我需要这个: 如果用户关闭了最后一个文档,我需要对我的加载项工具栏进行一些清理。但是,如果我在 DocumentBeforeClose 事件中进行清理并且用户单击取消,则加载项工具栏状态不正确。

编辑/更新:

正如 Rob Allen 所建议的,我现在使用 ShutDown 事件来清理我的父对象,并使用 BeforeClose 事件来对我的父对象进行预关闭验证。我的验证需要保存文档并尝试在 BeforeClose 调用的方法中执行此操作。如果以前从未保存过该文档,则会出现“另存为”对话框。如果用户单击取消,则会抛出 COMException,我会捕捉到它。然后出现保存/不保存/取消对话框。 如果用户单击“不保存”,则不会触发 ShutDown 事件。如果用户从“另存为”对话框保存,从第二个对话框保存,或在第二个对话框中点击取消,一切正常.

private void WordDocument_BeforeClose(object sender, System.ComponentModel.CancelEventArgs e)
{
  try
  {
    this.WordDocument.Save();
  }
  catch (System.Runtime.InteropServices.COMException a)
  {
    log.Error(a.Message);
  }
}

private void WordDocument_Shutdown(Object sender, EventArgs e)
{
  // Parent cleanup.
}

最佳答案

改为尝试文档关闭事件。文档 here

来自“备注”部分:

This is the last event to be called in a Document as it unloads. Use this event for any additional clean up.

In a document-level customization, the application domain for the assembly unloads when the document host item shuts down.

In an application-level add-in, the application domain does not unload when the document host item shuts down. Also, the underlying document object is no more available. To access the document before it shuts down use CloseEvent instead.

关于c# - 从保存对话框中捕捉取消状态,以获取即将关闭且未保存更改的 MS Word 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12588188/

相关文章:

c# - svcutil.exe 是 xsd.exe 的替代品吗?

c# - 从 HQL 返回额外数据

python - 从 Microsoft Word 获取拼写错误的单词

python - 在 Python 中从 Word 文档 (.docx) 中提取突出显示的单词

c# - <example></example> XML 注释标记 : how to see it?

c# - 使用普通参数和泛型参数重载构造函数

.net - 如何等待 Azure 搜索完成索引文档?用于集成测试目的

.net - 如何并行运行 linqpad 2.x 和 4.x?

c# - WPF 动态 DataGrid 绑定(bind)值从集合中的嵌套对象到自定义 DataGridCell 模板

c# - 使用 C# 从 MS Word 中的加载项访问 RichTextContentControl 文本