Tuesday, September 13, 2005

Starting Word Programmatically

When Word starts it locks the default template (normal.dot). When you start a second instance of Word, the second instance will notify you that the file is locked and the first instance will tell you that the default template has been changed by another Word session. When you start the Word application it will automatically reuse an existing instance but if you start an instance programmatically you have to do that yourself.

/// <summary>
/// This function will return a word application object,
/// either the one that is already running or a new one.
/// </summary>
/// <param name="PbReusedExistingWordApplication">
/// True if an existing word application is returned
/// </param>
/// <returns>
/// The Word application
/// </returns>
private static Word.ApplicationClass GetOrStartWordApplication(
    out bool PbReusedExistingWordApplication)
    Word.ApplicationClass LobjWordApplication = null;

    // Check if the Word process is running
    if (Process.GetProcessesByName("WINWORD").Length != 0)
        // Get a pointer to the Word application
        object LobjWordApplicationAsObject =

        if (LobjWordApplicationAsObject == null)
            throw new ApplicationException(
                "Unable to attach to the running Microsoft Word");

        LobjWordApplication =
            LobjWordApplicationAsObject as Word.ApplicationClass;
        PbReusedExistingWordApplication = true;
        // Create a new instance of the word application
        LobjWordApplication = new Word.ApplicationClass();
        PbReusedExistingWordApplication = false;

    return LobjWordApplication;

The function can either be used directly or you can wrap it in a utility class with an Open and Close function which stores the reused Boolean internally and depending on it either closes Word or leave it open.

So how do you handle people like me who can't wait for the app to start?

While the app is launching decided to continue doing some work in my already opened Word Document, cutting, copying and pasting stuff in and out of the document?

Keeping reference of documents available to be sure you don't close the document I worked on the last four hours? ;-)
Hi Maarten,

Thanks for the feedback :-)

You are right, I only considered the scenario in which Word is used for a very short time. If the user should be able to interact with Word it is better not to consider closing Word, or as you suggested, carefully keeping track of the documents opened in Word.

Actually this is not very hard to do, just close the documents created by the automation application. If there is still another document open, do not close Word.

I think this works in all scenarios, so I will use it also in my code if you do not mind ;-)
Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?