Getting excel application process id

23,188
using Excel = Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;
using System.Diagnostics;

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

    Process GetExcelProcess(Excel.Application excelApp)
    {
        int id;
        GetWindowThreadProcessId(excelApp.Hwnd, out id);
        return Process.GetProcessById(id);
    }
}
Share:
23,188
yoavba
Author by

yoavba

Updated on March 22, 2020

Comments

  • yoavba
    yoavba about 4 years

    I am creating an excel application with c#. Since I will maintain the excel file in urgency I want to keep its handler open. I want to keep the excel process id so I will be able to kill it in case the system crashs.

    How can I get the Excel Pid when creating it?

  • Erwin Raets
    Erwin Raets about 12 years
    Probably downvoted because it doesn't answer the question! If Excel goes out to lunch, which it often does, releasing all your references to it is not going to kill it. You NEED the process id.
  • Erwin Raets
    Erwin Raets about 12 years
    Yes, you do. Excel processes started through COM are not child processes of your process, they are children of svchost.exe. If Excel is performing a blocking operation such as QueryTable.Refresh(), and your process exits, excel.exe will not die. If you're doing those refreshes in threads or subprocesses, which you might need to terminate, you're doomed to accumulate zombie excel processes, UNLESS you can track their process id's and kill them.
  • Shai
    Shai about 12 years
    @NoahYetter I've been working with Excel through COM for the past 3 years and have never had problems with zombie processes using this code.
  • Erwin Raets
    Erwin Raets about 12 years
    Have you ever used QueryTable.Refresh()? Seriously, try it. Create a thread or subprocess, launch excel, load a workbook, start a long-running Refresh(), then terminate your thread/process. Instant zombie excel.