Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
Home
DiscussionsAccessExcelInfoPathOutlookPowerPointPublisherWord
DirectoryUser Groups
Related Topics
Outlook ExpressInternet ExplorerWindowsMS Server ProductsMore Topics ...

MS Office Forum / Word / Programming / September 2007

Tip: Looking for answers? Try searching our database.

How to dismiass Microsoft Office Word "Do you want to save the cha

Thread view: 
Enable EMail Alerts  Start New Thread
Thread rating: 
skywalker - 17 Sep 2007 01:46 GMT
Hi:
This is the third place I post the same question. In the previous two, the
mediators all said posted in the wrong location. Hopefully the third time is
a charm and get helps.

My application will generate a word document as report. The application
created Word Application and Document objects.

When users click on Close or the "X" icon on the up right corner. The
application will intercept word DocumentBeforeCloseEvent, to ask users Save,
No or Cancel to the document changes. Everything works fine except when
users
click on "Cancel", Word still displays it's own Dialog for users to select
Yes, No or Cancel for saving the document changes.

 
Is there anyway to prevent this Word dialog because my application already
process uses decision?

Here is part of the code:

Word_DocumentBeforeClose is used to process users decision.
The last part of If in else is to process when Cancel is clicked.

namespace HandleWordEvnts
{
    public partial class Form1 : Form
    {
        #region properties
        Word.ApplicationClass wordApp;
        Word.Document wordDoc;
        string docName;
        #endregion properties
 

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //===== Create a new document in Word ==============
            // Create an instance of Word and make it visible.
            wordApp = new Word.ApplicationClass();
            wordApp.Visible = true;

            // Local declarations.
            Object oMissing = System.Reflection.Missing.Value;

            // Add a new document.
            wordDoc = wordApp.Documents.Add(ref oMissing, ref oMissing,
                ref oMissing, ref oMissing); // Clean document

            // Add text to the new document.
            wordDoc.Content.Text = "Handle Events for Microsoft Word Using
C#.";
            docName = wordDoc.Name;

            //============ Set up the event handlers ===============
            wordApp.DocumentBeforeClose +=
                new Word.ApplicationEvents2_DocumentBeforeCloseEventHandler(
                Word_DocumentBeforeClose);
        }

        // The event handlers.
        private DialogResult showSaveFileDlg(ref string fileName, ref string
filePath)
        {
            DialogResult dlgRes = DialogResult.None;
            object locker = new object();
            Thread.Sleep(1000); //time needed for dialog to display
            lock (locker)
            {
                saveFileDialog1.Title = "App Save As";
                saveFileDialog1.FileName = filePath != "" ? (filePath + "\\"
+ fileName) : fileName; //init full name

                saveFileDialog1.InitialDirectory = filePath;
                saveFileDialog1.Filter = "Word Document (*.doc)|*.doc| Plain
Text (*.txt)|*.txt|All files (*.*)|*.*";

                saveFileDialog1.FilterIndex = 1;
                saveFileDialog1.RestoreDirectory = true;
                dlgRes = saveFileDialog1.ShowDialog();
                if (dlgRes == DialogResult.Cancel) return dlgRes;
                fileName =

saveFileDialog1.FileName.Substring(saveFileDialog1.FileName.LastIndexOf("\\")
+ 1);
                filePath = saveFileDialog1.FileName.Substring(0,
saveFileDialog1.FileName.LastIndexOf("\\"));
                return dlgRes;
            }
        }

        private void Word_DocumentBeforeClose(Word.Document doc, ref bool
Cancel)
        {
            docName = doc.Name;
            string fileName = doc.Name;
            string filePath = doc.Path;

            // ask user to save or not
            DialogResult dlgRes = DialogResult.None;
            AskSaveCnanges askSave = new AskSaveCnanges();
            askSave.setTxtBox1 = filePath != "" ? (filePath + "\\" +
fileName) : fileName;
            askSave.setTxtBox1Readonly = true;
            askSave.ShowDialog();
            if (askSave.DlgRes == DialogResult.Yes) //user agrees to save
            {
                Thread showWordDlg = new Thread(delegate() { dlgRes =
showSaveFileDlg(ref fileName, ref filePath); });
                showWordDlg.SetApartmentState(ApartmentState.STA);
                showWordDlg.Name = "DocClose";
                showWordDlg.Start();
                showWordDlg.Join();

                if (dlgRes == DialogResult.OK) //user agrees to save
                {
                    MessageBox.Show("DocumentBeforeClose ( Saved " +
doc.Name + " )","APP");

                    //Save the file, use default values except for filename
                    object ofileName = filePath + "\\" + fileName;
                    object optional = Missing.Value;
                    try
                    {
                        doc.SaveAs(ref ofileName, ref optional, ref
optional, ref optional,
                            ref optional, ref optional, ref optional,
                            ref optional, ref optional, ref optional, ref
optional);

                        doc.Saved = true;
                        object saveChanges = true;
                        object originalFormat = Missing.Value;
                        object routeDocument = Missing.Value;
                        wordApp.Quit(ref saveChanges, ref originalFormat,
ref routeDocument);
                    }
                    catch (COMException e)
                    {
                        MessageBox.Show(e.Message,"ApP.DocumentBeforeClose");
                    }
                }
            }
            else if (askSave.DlgRes == DialogResult.No)
            {
                MessageBox.Show("DocumentBeforeClose ( Not Saved " +
doc.Name + " )","APP");
                Cancel = true;
                object saveChanges = false;
                object originalFormat = Missing.Value;
                object routeDocument = Missing.Value;
                doc.Close(ref saveChanges, ref originalFormat, ref
routeDocument);
                wordApp.Quit(ref saveChanges, ref originalFormat, ref
routeDocument);
            }
            else
            {
                MessageBox.Show("DocumentBeforeClose ( Canceled " + doc.Name
+ " )","APP");

 //When users cilck on Cancel button.
 // Cancel is set to true but Word still displays it's own dialog.
                Cancel = true;
                doc.Saved = false;
                wordApp.Activate();
                Thread.Sleep(5000);
 //send key does not work either
                SendKeys.SendWait("{RIGHT}{RIGHT}{ENTER}");
            }
        }
 }
Russ - 17 Sep 2007 05:23 GMT
This is a VBA forum so here is something you can research.
Using Events with the Document Object:
<http://msdn2.microsoft.com/en-us/library/aa211933(office.11).aspx>
Using Events with the Application Object:
<http://msdn2.microsoft.com/en-us/library/aa211915(office.11).aspx>

If you follow their steps in Word VBA Editor, you may see the drop down list
of events for the Application and the actual **Close** event might be the
one to intercept in order not to see the unwanted Word Close dialog.

> Hi:
> This is the third place I post the same question. In the previous two, the
[quoted text clipped - 173 lines]
>          }
>   }

Signature

Russ

drsmN0SPAMikleAThotmailD0Tcom.INVALID

Russ - 17 Sep 2007 05:38 GMT
Usually Word does not prompt to save documents if they have been saved
recently and no new changes have occurred.
You force a close without saving changes by using:
ActiveDocument.Saved = True
ActiveDocument.Close

Or from VBA Help:

Closing documents
To close a single document, use the Close method with a Document object. The
following instruction closes and saves the document named Sales.doc.
Documents("Sales.doc").Close SaveChanges:=wdSaveChanges
You can close all open documents by applying the Close method to the
Documents collection. The following instruction closes all documents without
saving changes.
Documents.Close SaveChanges:=wdDoNotSaveChanges
The following example prompts the user to save each document before the
document is closed.
For Each aDoc In Documents
   aDoc.Save NoPrompt:=False
   aDoc.Close
Next

> This is a VBA forum so here is something you can research.
> Using Events with the Document Object:
[quoted text clipped - 184 lines]
>>          }
>>   }

Signature

Russ

drsmN0SPAMikleAThotmailD0Tcom.INVALID

 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.