11

I have a c# simple application that have to write some values in a excel ranges of a specific worksheet. I create an instance of Excel application if not exist, but if exist i want to set active it and take an instance if it to use in my code.

I use this code to create a new application:

Microsoft.Office.Interop.Excel app = 
   new Microsoft.Office.Interop.Excel.Application();
app.Visible = true;

To get the handle of active excel window i use this api

[DllImportAttribute("User32.dll")]
private static extern int FindWindow(String ClassName, String WindowName);

How can i get an instance of excel application by an handle?

int hWnd = FindWindow(null, "Microsoft Excel - MySheet.xlsx");
Microsoft.Office.Interop.Excel app = ....(hWnd)
Kiquenet
  • 14,494
  • 35
  • 148
  • 243
Babba
  • 253
  • 1
  • 5
  • 12

3 Answers3

23

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;
}
James
  • 80,725
  • 18
  • 167
  • 237
  • 1
    For me, `instance = new Excel.ApplicationClass();` didn't work. I had to use `instance = new Excel.Application();`. – David Murdoch Jul 31 '13 at 15:12
  • 2
    @DavidMurdoch this is the result of a [change in VS2010 for embedding interop types](http://blogs.msdn.com/b/mshneer/archive/2009/12/07/interop-type-xxx-cannot-be-embedded-use-the-applicable-interface-instead.aspx). Switching to `Application()` over `ApplicationClass()` is a workaround, you get the same result (even though it looks like you are instantiating an interface!). – James Jul 31 '13 at 15:30
15

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.

Govert
  • 16,387
  • 4
  • 60
  • 70
2

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

Shiraz Bhaiji
  • 64,065
  • 34
  • 143
  • 252