Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
600 views
in Technique[技术] by (71.8m points)

c# - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...