Abiel
Abiel

Reputation: 5455

Get Excel.Application object from Process or hwnd in .NET

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.

Upvotes: 5

Views: 18680

Answers (3)

JamesFaix
JamesFaix

Reputation: 8655

I've created a class that can iterate through all running Excel instances, and also lookup Application instances by Hwnd, ProcessID, or a Process object.

http://www.codeproject.com/Tips/1080611/Get-a-Collection-of-All-Running-Excel-Instances

The answer is basically a lot of ugly extern calls to the Win32 API, which are best left hidden behind a clean public interface.

This has not been tested on all version of Excel or Windows.

Upvotes: 1

code4life
code4life

Reputation: 15794

Answered on another SO post:

How to get Excel instance or Excel instance CLSID using the Process ID?

Upvotes: 2

Gant
Gant

Reputation: 29889

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.

Upvotes: 2

Related Questions