Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

excel

I'm working with C#, I need to obtain a specific instance of excel by it's process ID; I get the Process ID of the instance that I need from another application but I don't know what else to do, I don't know how can I get a running instance of excel given his process ID.

I have researched a lot on the web, but I have only see examples of using Marshal.GetActiveObject(...) or Marshal.BindToMoniker(...), which I can't use since the first one returns the first Excel instance registered in the ROT and not precisely the one that I need, and the second one requires that you save the excel file before trying to get the instance.

Also, if I where able to get the CLSID of the excel instance that I need, using the process ID, then I may be able to call

GetActiveObject(ref _guid, _ptr, out objApp);

that ultimately will return the excel instance that I need.

like image 264
Vic Avatar asked Apr 20 '09 21:04

Vic


2 Answers

Once you identify the process via the process id, you can get the Process.MainWindowHandle and then use that along with the AccessibleObjectFromWindow API to get access to the Excel object model for that process.

The article Getting the Application Object in a Shimmed Automation Add-in by Andrew Whitechapel describes this technique in detail, along with sample code.

The key code in that article for you begins at the line:

int hwnd = (int)Process.GetCurrentProcess().MainWindowHandle

Which in your case might look more like:

int excelId = 1234; // Change as appropriate!
int hwnd = (int)Process.GetProcessById(excelId).MainWindowHandle

where the 'excelId' is the process id number that you are looking for. Otherwise, the code should be essentially the same as given in the article. (Ignore the fact that his code is written for an add-in; that aspect won't affect your needs here, so just ignore it.)

If you do not have the process id, then you you would want to use Process.GetProcessesByName, whereby you could enumerate each one and grab control of each Excel instance with access to the object model, as needed.

Hope this helps,

Mike

like image 51
Mike Rosenblum Avatar answered Nov 05 '22 18:11

Mike Rosenblum


The ROT entries are not tagged with a CLSID. The ROT returns a DWORD from Register, which is used as a identifier for Unregister. I've run into this problem before and the only way I've solved it is to have some kind of add-in loaded into each Excel that you can communicate directly with.

like image 44
Joel Lucsy Avatar answered Nov 05 '22 17:11

Joel Lucsy