Click to See Complete Forum and Search --> : Can events be hooked to MS Word?


kobus
April 10th, 2006, 02:13 AM
Hi

I am opening a MS Word document using C# code.


Word.ApplicationClass WordApp = new Word.ApplicationClass();

// Use the open file dialog to choose a word document
if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
{
object fileName = openFileDialog1.FileName;
object readOnly = false;
object isVisible = true;

//Here is the way to handle parameters you don't care about in .NET
object missing = System.Reflection.Missing.Value;

//Make word visible, so you can see what's happening
WordApp.Visible = true;

//Open the document that was chosen by the dialog
Word.Document aDoc = WordApp.Documents.Open(ref fileName, ref missing,ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref isVisible);


//Activate the document so it shows up in front
aDoc.Activate();
}


This works fine and it opens the document in MS Word separate from the C# application. Is there a way of hooking an event to the document object (aDoc) so that when the word document is closed the C# application can react to the event?

Thanks
Kobus

stepi
April 10th, 2006, 03:09 AM
Hi,
Yep the events are available. Here is an example


WordApp.ApplicationEvents3_Event_DocumentBeforeClose+=new Word.ApplicationEvents3_DocumentBeforeCloseEventHandler(wd_ApplicationEvents3_Event_DocumentBeforeClose);

..............

void wd_ApplicationEvents3_Event_DocumentBeforeClose(Word.Document Doc, ref bool Cancel)
{
................
}

kobus
April 10th, 2006, 06:07 AM
Hi stepi

Thanks for the post. This works well when the whole MS Word application is closed. Is there anything similar for when only a particular document in the MS Word application is closed? I cannot seem to find anything like that. If not, would a person be able to write an event for that?

Thanks.

stepi
April 10th, 2006, 06:41 AM
Hi again,
There is no event on the Document class that will tell you when it is closing. You can use though this event at application level. You will need a work around to identify your document. You are opening the document so you have aDoc as reference to you word document.


Word.Document aDoc;
...............

void wd_ApplicationEvents3_Event_DocumentBeforeClose(Word.Document Doc, ref bool Cancel)
{
if(Doc == aDoc)
{
//your special routine
}
}


You can use the document name to identify your document, but i don't find this solution reliable.