title: Wait for Excel Interlop to Exit in C#
body: <p>I am working on a tool which will automate a couple of actions for me. One of these actions is download an excel file, run a macro on it and then mail the file. In some cases i want the tool to just run the excel macro, then after x seconds exit excel and mail the file. This all works fine since i can just wait for fixed period of time. However, in some cases i want the to be able to check and change the data which has been retrieved by the excel macro. When this is the case i want to keep excel open until the used manually closes excel. When i detect excel is no longer opened i want to mail the file.</p>
  
  <p>This last case gives me some trouble. Because i use the excel interlop to open excel, i cannot i am not able to use the WaitForExit() like i can with a normal process. When i manually close excel the process also keeps running in the process explorer. </p>
  
  <p>I have searched for solutions on the internet but none of them really work. Is there any way i can achieve this in a simple way?</p>
  
  <p><em><strong>UPDATE</em></strong>
  Thanks a lot for your reply, It really helped me. Waiting for excel now works correcly. I used the following code:</p>
  
  <pre><code>if (Settings.ExitExcel)
  {
    System.Threading.Thread.Sleep(Settings.ExcelTimeout * 1000);
  
    //Close Excel
    excelWorkbook.Close();
    excelApp.Quit();
  }
  else
  {
    Excel.AppEvents_WorkbookBeforeCloseEventHandler Event_BeforeBookClose;
  
    Event_BeforeBookClose = new Excel.AppEvents_WorkbookBeforeCloseEventHandler(WorkbookBeforeClose);
    excelApp.WorkbookBeforeClose += Event_BeforeBookClose;
  
    //Wait until excel is closed
    while (!isClosed)
    {
      Thread.Sleep(1000);
    }
  
    //Show message               
    MessageBox.Show("excel closed");
  }
  
  //Clean up excel.
  Marshal.FinalReleaseComObject(excelSheets);
  Marshal.FinalReleaseComObject(excelWorksheet);
  Marshal.FinalReleaseComObject(excelWorkbook);
  Marshal.FinalReleaseComObject(excelApp);
  excelApp = null;
  excelWorkbook = null;
  excelWorksheet = null;
  excelSheets = null;
  GC.Collect();     
  </code></pre>
  
  <p>Only problem now is that excel still keeps running in the processes. Am i not closing it correctly?</p>