tags:

views:

112

answers:

2

In C# I am trying to get an instance of an Excel.Application object from a Process object. This seems like it should be really simple yet I cannot figure it out and cannot find an example. To repeat, I have a System.Diagnostics.Process object that I know refers to a running Excel instance. I now need to recover a Microsoft.Office.Interop.Excel.Application object that refers to the process so that I can go about manipulating the Excel application from C#.

In case it makes it any simpler, I also have the HWND id and window text associated with the active Excel window.

Thanks.

+1  A: 

How to use Visual C# to automate a running instance of an Office program

using Excel = Microsoft.Office.Interop.Excel;
:    

private void button1_Click(object sender, System.EventArgs e)
{

    //Excel Application Object
    Excel.Application oExcelApp;

    this.Activate();

    //Get reference to Excel.Application from the ROT.
    oExcelApp =  (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");

    //Display the name of the object.
    MessageBox.Show(oExcelApp.ActiveWorkbook.Name);

    //Release the reference.
    oExcelApp = null;
}

Not sure if you strictly need to retrieve application object from the Process class? Hope this helps.

m3rLinEz
Sorry, I should have mentioned that I have already considered this option. Unfortunately this common approach does not work for me because I need to be able to get the last active Excel window regardless of how many instances of Excel there are running. GetActiveObject will always deliver a reference to the same Excel instance even if there are multiple instances running.
Abiel
A: 

Answered on another SO post:

http://stackoverflow.com/questions/770173/how-to-get-excel-instance-or-excel-instance-clsid-using-the-process-id

code4life
Thanks very much. I was able to get this to work.
Abiel