开发者

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 开发者_JAVA百科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.


Answered on another SO post:

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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜