Start Word and monitor if document closed

3.1k views Asked by At

we need for our school project a way to start a word instance and track if the document was closed. The COM api from word doens't have a event for this, are there any other ways to do this?

Currently we're using the COM api from word, but everything else would be fine. We're programing in C#.

2

There are 2 answers

3
Koen On

If your using the Microsoft.Office.Interop.Word library there is an event you can subscribe too:

Microsoft.Office.Interop.Word.Application wordApp =
    new Microsoft.Office.Interop.Word.Application();
wordApp.DocumentBeforeClose +=
    new ApplicationEvents4_DocumentBeforeCloseEventHandler(
        wordApp_DocumentBeforeClose);

...

private void wordApp_DocumentBeforeClose(Document Doc, ref bool Cancel)
{
    // Do your thing
}

Edit:

To take care of the file lock ==> take a look at this post. As you can see there are a few things done in the DocumentBeforeClose:

  1. Check if the document is saved. If not ==> ask where to save it and do it yourself.
  2. Close the document yourself
  3. Close Word

After these things are taken care of, you can do your stuff. The lock should be released.

3
hungryMind On

Use the winword process to check if process running on particual file is exited or not.

If you dont know the process of newly started instance use this or simply hook exited event of process.

Get all word processes

var info = Process.GetProcessesByName("winword").FirstOrDefault();

Identify the process of particular file using Process.MainWindowTitle

Hook exited event of the process Process.Exited