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

前端 未结 3 1836
一向
一向 2020-12-08 16:59

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\

相关标签:
3条回答
  • 2020-12-08 17:29
    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.

    0 讨论(0)
  • 2020-12-08 17:43

    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

    0 讨论(0)
  • 2020-12-08 17:51

    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.

    0 讨论(0)
提交回复
热议问题