Access Excel VSTO COM Addin from child process (console app)

109 views Asked by At

What I'm looking to do is to be able to launch a child process (with elevated privileges) from my VSTO COMAddin that can access the COMAddin object for the process that spawned it.

More specifically, I want to be able to kill the addin (via COMAddin.Connect = false), do the work that requires the privileges and then restart the addin.

Using a second addin I can accomplish this, as I have access to the Application.COMAddIns collection (second addin would shutdown the first when required, start the privileged process and restart the first addin when it completes). I'd rather not have 2 separate addins to accomplish this though if at all possible.

I also know that I can start a new instance of Excel with new Excel.Application() and access the COMAddIns from there, however I don't want a new instance, I want to be able to control the addin from the running instance.

Any help/ideas are appreciated.

1

There are 1 answers

0
Eugene Astafiev On

You can get the Excel running instance from an external application by using the GetActiveObject function which uses the Running Object Table (ROT) for getting an active Excel instance and would give you the last Excel instance that was opened - not necessarily the one corresponding with the window handle you have.

public Excel.Application StartExcel()
{
    Excel.Application instance = null;
    try
    {
       instance = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
    }
    catch (System.Runtime.InteropServices.COMException ex)
    {
       instance = new Excel.ApplicationClass();
    }

    return instance;
}

You may also find the AccessibleObjectFromWindow function helpful which retrieves the address of the specified interface for the object associated with the specified window.. See How to use use late binding to get excel instance? for more information.


Note, you can access your add-in methods and properties from other applications. Read more about that in the Call code in VSTO Add-ins from other Office solutions article.