How can I get the ProcessID (PID) for a hidden instance of an Excel application

I have an instance of Microsoft.Office.Interop.Excel.Application . To ensure that the EXCEL.EXE process freezes in time, I need to find the ProcessID that was created when the Application object was created.

I found samples for this when Excel Application has a window.

Is there a way to do this for a "hidden" instance, i.e. when there is no window associated with the EXCEL.EXE process, that is, when excelApp.Hwnd not installed?

0
c # winapi excel
Jun 05 '16 at 0:31
source share
1 answer

Application.Hwnd has a valid window handle that you can use to get the process for the associated Excel application, even if the application does not have a visible workbook window.

 [DllImport("user32.dll")] static extern int GetWindowThreadProcessId(int hWnd, out int lpdwProcessId); Process GetExcelProcess(Microsoft.Office.Interop.Excel.Application excelApp) { int id; GetWindowThreadProcessId(excelApp.Hwnd, out id); return Process.GetProcessById(id); } void TerminateExcelProcess(Microsoft.Office.Interop.Excel.Application excelApp) { var process = GetExcelProcess(excelApp); if (process != null) { process.Kill(); } } private void button1_Click(object sender, EventArgs e) { // Create Instance of Excel Microsoft.Office.Interop.Excel.Application oXL = new Microsoft.Office.Interop.Excel.Application(); try { // Work with oXL } finally { TerminateExcelProcess(oXL); } } 



Note. There are several answers on this question explaining why the Excel process will not end when you finish working with it with C # through automation (if you are not very pedantic that you release every link to any object that you use explicitly).

+1
Jun 05 '16 at 12:44
source share



All Articles