Kill Process Excel C#

后端 未结 10 1478
栀梦
栀梦 2020-12-09 12:45

I have to 2 process excel. For example:

1) example1.xlsx 2) example2.xlsx

How to kill first \"example1.xlsx\"?

I use this code:

   f         


        
10条回答
  •  有刺的猬
    2020-12-09 13:05

    In the namespace section add this using statement.

    using System.Diagnostics;
    

    This example instantiated Excel with this:

    _Application excel = new _Excel.Application();
    

    This method kills the right Excel task by using the window handle.

        public void Kill()
        {
            Int32 ExcelHwnd = excel.Hwnd;
            Process[] localExcel = Process.GetProcessesByName("EXCEL");
            foreach (Process Pgm in localExcel)
            {
                // xlMinimized keeps the screen from flashing when the user interface is made 
                // visible with the excel.visible needed to set the MainWindowHandle
                excel.WindowState = XlWindowState.xlMinimized;
                excel.Visible = true;
                if ((Pgm.ProcessName == "EXCEL") && (ExcelHwnd == Pgm.MainWindowHandle.ToInt32()))
                {
                    Pgm.Kill();
                }
            }
        }
    

    This worked without fail.

提交回复
热议问题