0
votes

I have an application that opens new Word documents, lets users update and save, then they can close Word by clicking X in upper right, or they can close word from the application.

Issue comes when user makes edits, clicks X in upper right of Word, Save Dialog displays, user forgets to click save, but then tries to close document from application. Application thinks it successfully closed document using this line of code:

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

But dialog is still open and doc has not closed. No exceptions or warnings in code.

Is there a way to check for existing open dialog windows and circumvent open dialog boxes with code?

1

1 Answers

1
votes

This is not my ideal solution to this problem, but for now, it works...

When a dialog window is open at the time you wish to close a document, you can catch a COMException and read the HResult ID to control how you react to the exception. Here is what I found for the Open Dialog issue as well as Word closing unexpectedly.

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;

                }
            }