How to access Microsoft Word existing instance using late binding

Grant picture Grant · Feb 5, 2010 · Viewed 10.8k times · Source

i am developing some code in c# where i will be interacting with Microsoft Word. I want to be able to have the option of re-using an existing instance or as an alternative creating a new instance.

Keeping in mind i want to do all of this using LATE BINDING... it is safe to say i have figured out how to get things working when creating a new instance.. i just call Activator.CreateInstance etc..

The problem i am having is how do i reuse an existing instance, for example, Word is already open and i want to use that instance.

Is there an Activator.UseExistingInstance? or something similar??

Thanks!

Answer

Foole picture Foole · Feb 5, 2010

You're looking for Marshal.GetActiveObject.

object word;
try
{
    word = System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application");
}
catch (COMException)
{
    Type type = Type.GetTypeFromProgID("Word.Application");
    word = System.Activator.CreateInstance(type);
}