Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

excel

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.

like image 265
Abiel Avatar asked Jun 08 '10 04:06

Abiel


3 Answers

Answered on another SO post:

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

like image 177
code4life Avatar answered Nov 08 '22 14:11

code4life


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.

like image 2
Gant Avatar answered Nov 08 '22 14:11

Gant


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.

like image 1
JamesFaix Avatar answered Nov 08 '22 16:11

JamesFaix