如何在关闭 Word 文档之前检查打开的对话框?

How to check for open dialog before closing Word Document?

我有一个应用程序可以打开新的 Word 文档,让用户更新和保存,然后他们可以通过单击右上角的 X 关闭 Word,或者他们可以从应用程序中关闭 word。

当用户进行编辑时出现问题,单击 Word 右上角的 X,显示保存对话框,用户忘记单击保存,但随后尝试从应用程序关闭文档。应用程序认为它使用这行代码成功关闭了文档:

WordApp.Documents[docUri].Close(WdSaveOptions.wdDoNotSaveChanges);

但是对话框仍然打开,文档还没有关闭。代码中没有异常或警告。

有没有办法检查现有打开的对话框 windows 并用代码绕过打开的对话框?

这不是我对这个问题的理想解决方案,但就目前而言,它有效...

当对话框 window 在您希望关闭文​​档时打开时,您可以捕获 COMException 并读取 HResult ID 以控制您对异常的反应方式。以下是我发现的打开对话框问题以及 Word 意外关闭问题。

catch (System.Runtime.InteropServices.COMException ex)
            {
                switch (ex.HResult)
                {
                    case -2147417846:  //Dialog box is open and blocking us
                        context.Clients.All.addMessage("CloseWord", "Can't close Word, please check for open dialog box");
                        return;

                    case -2147023174:  //Word Instance died without us knowing, need to set back to null to recover
                        context.Clients.All.addMessage("CloseWord", "Word Failed, attempting to recover...");
                        break;

                    default:  //this is to catch the unknown and bubble up the details
                        context.Clients.All.addMessage(
                            string.Format("CloseWord", "Oops... Something went wrong  Code {0}  Message: {1}", ex.HResult, ex.Message));
                        return;

                }
            }