Get instance of Excel application with C# by Handle

Use the following code to get the first running instance of Excel:

oExcelApp =  (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");

Example

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;
}

There might be more than one Excel instance running.

GetActiveObject(...) looks in the Running Object Table (ROT) and would give you the last Excel instance that was opened - not necessarily the one corresponding with the window handle you have.

You're looking for AccessibleObjectFromWindow(..). The Andrew Whitechapel post linked to in the other answer shows how to use this function.

Another link - http://blogs.officezealot.com/whitechapel/archive/2005/04/10/4514.aspx.


You can use Marshal.GetActiveObject, see this blog post for details:

http://blogs.msdn.com/andreww/archive/2008/11/30/starting-or-connecting-to-office-apps.aspx