If you are using COM objects like Microsoft Excel or Microsoft PowerPoint, you may sometime notice that the COM instances are not releasing from the process list; even though you called Close(), Quit() on the application instance.

 

In case you faced the same issue, this post will guide you to find the Process ID (from the HWND) of that particular instance to take further action to release it.

 

Here's how to retrieve Process details of Excel, PowerPoint app instance

 

The DllImport attribute in .NET is very useful when you want to reuse an existing unmanaged code in a managed application. It provides the information needed to call a function exported from an unmanaged DLL. You can find this under the 'System.Runtime.InteropServices' namespace, named as 'DllImportAttribute'.

 

To get the process ID, based on handler of the Microsoft Excel or Microsoft PowerPoint application instance, you need to import 'user32.dll' via DllImport and then use the Win32 API 'GetWindowThreadProcessId'.

 

The 'GetWindowThreadProcessId' takes an integer parameter of application handler (HWND) and returns the process ID as out parameter. The extern modifier is used to declare the method which is implemented externally in a managed DLL.

 

 

You can declare it as follow, to import the unamanged API GetWindowThreadProcessId and use it to retrieve the process ID:

 

[DllImport("user32.dll")]
static extern int GetWindowThreadProcessId(int hWnd, out int lpdwProcessId);

 

Then retrieve the HWND from the PowerPoint application instance or Excel application instance, that you created in your C# code. Pass that value to the GetWindowThreadProcessId method as first parameter and retrive the desired process ID of the same instance via the out parameter. Here's the code snippet for your reference:

 

    var applicationHwnd = powerpointApp.HWND;
    var processID = GetProcessIdBy(applicationHwnd);
    .
    .
    .
    private static int GetProcessIdBy(int hwnd)
    {
        int processId = 0;
        GetWindowThreadProcessId(hwnd, out processId);
        return processId;
    }

 

Point to Note: The same concept is not applicable for Microsoft Word application instance, as the Microsoft Automation API for Word does not provide relevant data like HWND; which is available for Excel and PowerPoint.

 

Now, once you have the process ID, you can easily retrieve the process and perform your desire operation on it. I hope that the above code snippet was useful. Do let me know, if you are facing any issues or have any further queries.

 

 

Have a question? Or, a comment? Let's Discuss it below...

Thank you for visiting our website!

We value your engagement and would love to hear your thoughts. Don't forget to leave a comment below to share your feedback, opinions, or questions.

We believe in fostering an interactive and inclusive community, and your comments play a crucial role in creating that environment.