天天看点

c# 关闭excel进程

excel的application app,直接使用app.Quit();app=null;有时候不能完全关闭excel进程,而通过下面的Kill方法即Kill(app);则可以让正在处理的excel从进程中消失。

引用命名空间using System.Runtime.InteropServices;

        [DllImport("User32.dll", CharSet = CharSet.Auto)]

        public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID);

        public static void Kill(Microsoft.Office.Interop.Excel.Application excel)

        {

            IntPtr t = new IntPtr(excel.Hwnd);   //得到这个句柄,具体作用是得到这块内存入口

            int k = 0;

            GetWindowThreadProcessId(t, out k);   //得到本进程唯一标志k

            System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(k);   //得到对进程k的引用

            p.Kill();     //关闭进程k

        }

继续阅读