简体   繁体   中英

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

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.

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

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.

using System.Diagnostics;

   var eProcess = from p in Process.GetProcessesByName("EXCEL")
                   where p.Id == 3700 //whatever Id you have...
                   select p;

    foreach (var process in eProcess)
        process.Kill();

This gets all processes named "EXCEL" where the Process Id equals a specific value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM