Hari
Hari

Reputation: 11

I want to close a specific excel file amongst more then 2 open without Killing Excel process

I have three excel files (MS office 16) opened. My code check for a specific file if it is open then it try to closes it but it closes excel process which ultimately closes all the excel files.

What I noticed is in task manager there is only one EXCEL.EXE porcess for all the files and under Details tab I can see all my open excel file with name.

What I Tried is :

System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcesses("Excel");    
  foreach (Process p in processes)
  {
      if (p.MainWindowTitle == "MyFile.xlsx - Excel")
      {
          p.Kill();
          break;
      }
  }

and below code does nothing :

 Microsoft.Office.Interop.Excel.Application xlApp = new icrosoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(path);
            //xlWorkbook.Close(false);

            xlWorkbook.Close(true, Type.Missing, Type.Missing);
            xlApp.Quit();
            System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkbook);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
            xlWorkbook = null;
            xlApp = null;

            GC.Collect();

Upvotes: 1

Views: 613

Answers (1)

L. Scott Johnson
L. Scott Johnson

Reputation: 4412

Instead of killing the process, send a close message to the window:

System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcesses("Excel");    
foreach (Process p in processes)
{
  if (p.MainWindowTitle == "MyFile.xlsx - Excel")
  {
    int hwnd = 0;

    //Get a handle for the Application main window
    hwnd = FindWindow(null, p.MainWindowTitle);

    //send WM_CLOSE system message
    if (hwnd != 0)
      SendMessage(hwnd, WM_CLOSE, 0, IntPtr.Zero); 

    break;
  }
}

Upvotes: 1

Related Questions