peter
peter

Reputation: 1049

Word Document.Close does not show saving option dialog

I am writting word automation functions. My app let users click on a word document file name to open it; when users click another doc, it closes the previous one first, then opens the new one.

My problem is about closing a previous doc.

I tried _Application.Quit(WdSaveOptions.wdPromptToSaveChanges) first. It shows the saving option dialog, but it doesn't return to codes, so, a new doc could open before users' response to the dialog. That is not I want.

Sendmessage can close the Word with a saving dialog, and wait users response to the dialog. This is better than the _Application.Quit.

I like Document.Close(). It close the Document, but the Word application is not closed, so it is more quick to open the next doc than the _Application.Quit and Sendmessage.

The problem with the Document.Close is that it just saves the doc with changes without showing a saving option dialog, although I pass WdSaveOptions.wdPromptToSaveChanges as a parameter in Document.Close().

Are there some bugs in my codes or the close() has bugs itself? Thanks.


using System;
using System.Windows.Forms;
using System.IO;
using Word = Microsoft.Office.Interop.Word;
using System.Threading;
using System.Runtime.InteropServices;
using Microsoft.Office.Interop.Word;

namespace Test_IE_Doc
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        [DllImport("user32.dll")]
        static extern bool SetForegroundWindow(IntPtr hWnd);

        int FHwnd = 0;
        public Word._Application oWord;
        private void button1_Click(object sender, EventArgs e)
        {
            string fileName = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location), "1.docx");

            CloseDoc();

            Thread.Sleep(1000);

            if (oWord == null)
              oWord = new Word.Application();
            oWord.Visible = true;
            oWord.Documents.Open(fileName, true);
            FHwnd = oWord.Documents[1].ActiveWindow.Hwnd;
            oWord.WindowState = Word.WdWindowState.wdWindowStateNormal;
            SetForegroundWindow(new IntPtr(FHwnd));
        }

        private void CloseDoc()
        {
            if (FHwnd != 0)
                //oWord.Quit(WdSaveOptions.wdPromptToSaveChanges);
                oWord.Documents[1].ActiveWindow.Close(WdSaveOptions.wdPromptToSaveChanges);
        }
    }
}

Upvotes: 0

Views: 326

Answers (1)

peter
peter

Reputation: 1049

I use Documents.Saved to check if the document is changed, then ask user whether the user want to save it. then Document's ActiveWindow.Close() pass WdSaveOptions.wdSaveChanges for saving, pass WdSaveOptions.wdDoNotSaveChanges for not saving.

Upvotes: 0

Related Questions