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 =
            Marshal.GetActiveObject("Word.Application");

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

        LobjWordApplication =
            LobjWordApplicationAsObject as Word.ApplicationClass;
        PbReusedExistingWordApplication = true;
    }
    else
    {
        // 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.

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