Getting a Unique Instance of Word

I get this question from time to time. When you need to make sure you grab your own instance of Word and not attach to the existing instance of Word. Normally, when you launch Word with a “new Word.Application()” call, you will always get your own instance of Word. However, if the running instance of Word was started with the “winword.exe /automation” switch, you will actually attach to that instance of Word. I am not sure if this is the way the application was designed or if there is some type of a defect here, but it can cause real problems when you are expecting to get your own, clean instance of Word.

The following code can be added to your project to assure you have a unique instance. You simply do something like this:

public static void Main()
{
    Word.Application myWordInst = getWordInstance();
}

What the “getWordInstance()” method does is gets the number of running Word instances in memory. It then issues a new Automation request. If the number of instances of Word does not increase after the call, it will issue another Automation call – so on and so forth until the number of running Word processes in memory increases by one. Here is the case:

/// <summary>
/// Gets a clean Word instance
/// </summary>
/// <returns></returns>
private Word.Application getWordInstance()
{
    // get the count of Word instance in memory
    int LiCnt = getWordCount();
    // try to spawn a new one
    Word.Application wdApp = new Word.Application();
    // if there were no instances or the number of instances in
    // memory now is greater, then return our instance just
    // created...
    if (LiCnt == 0 || LiCnt < getWordCount())
        return wdApp;
    else
        // otherwise, return another new instance
        return new Word.Application();
}

/// <summary>
/// Gets the number of instance of Word in memory
/// </summary>
/// <returns></returns>
private int getWordCount()
{
    int LiCnt = 0;
    //find winword.exe in memmory and count it
    foreach (Process LobjProcess in Process.GetProcesses())
        if (LobjProcess.ProcessName.ToLower().Contains("winword"))
            LiCnt++;
    return LiCnt; // return the count
}

Leave a Reply