Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting excel application process id

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?

like image 783
yoavba Avatar asked Dec 13 '11 14:12

yoavba


1 Answers

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);
    }
}
like image 89
Nick Spreitzer Avatar answered Oct 25 '22 16:10

Nick Spreitzer