C# Excel進程關閉

來源:互聯網
上載者:User

 

using   System.Runtime.InteropServices;               [DllImport("User32.dll",   CharSet   =   CharSet.Auto)]       public   static   extern   int   GetWindowThreadProcessId(IntPtr   hwnd,   out   int   ID);       protected   void   Button1_Click(object   sender,   EventArgs   e)       {           Excel.ApplicationClass   excel   =   new   Microsoft.Office.Interop.Excel.ApplicationClass();           excel.Workbooks.Open("d:\aaa.xls",   Type.Missing,   Type.Missing,   Type.Missing,   Type.Missing,   Type.Missing,   Type.Missing,   Type.Missing,   Type.Missing,   Type.Missing,   Type.Missing,   Type.Missing,   Type.Missing,   Type.Missing,   Type.Missing);           IntPtr   t   =   new   IntPtr(excel.Hwnd);           int   k   =   0;           GetWindowThreadProcessId(t,   out   k);           System.Diagnostics.Process   p   =   System.Diagnostics.Process.GetProcessById(k);           p.Kill();                        }  

同時需要修改設定檔machine.config

<processModel   enable="true"   timeout="Infinite"   idleTimeout="Infinite"   shutdownTimeout="0:00:05"   requestLimit="Infinite"   requestQueueLimit="5000"   restartQueueLimit="10"   memoryLimit="60"   webGarden="false"   cpuMask="0xffffffff"   userName="System"   password="AutoGenerate"   logLevel="Errors"   clientConnectedCheck="0:00:05"   comAuthenticationLevel="Connect"   comImpersonationLevel="Impersonate"   responseRestartDeadlockInterval="00:09:00"   responseDeadlockInterval="00:03:00"   maxWorkerThreads="25"   maxIoThreads="25"/>   
  userName="machine"   改為   userName="System"

以上部分在Win2008中找不到 沒有設定成功

通過設定使用者權限,Asp.net類比使用者等方式任然無法殺掉Excel進程,最後的解決辦法是寫一個自動殺Excel進程的服務。

 

 

using System;using System.Diagnostics;using System.ServiceProcess;namespace KillExcel{    public partial class KillExcel : ServiceBase    {        public KillExcel()        {            InitializeComponent();        }        protected override void OnStart(string[] args)        {            // TODO: 在此處添加代碼以啟動服務。            double sleeptime =  60 * 1000; //1分鐘            System.Timers.Timer t = new System.Timers.Timer(sleeptime);//執行個體化Timer類,設定間隔時間為10000毫秒;             t.Elapsed += new System.Timers.ElapsedEventHandler(killExcel);//到達時間的時候執行事件;             t.AutoReset = true;//設定是執行一次(false)還是一直執行(true);             t.Enabled = true;//是否執行System.Timers.Timer.Elapsed事件;         }        public void killExcel(object source, System.Timers.ElapsedEventArgs e)        {            Process[] myProcesses;            DateTime startTime;            myProcesses = Process.GetProcessesByName("Excel");            //得不到Excel進程ID,暫時只能判斷進程啟動時間            foreach (Process myProcess in myProcesses)            {                startTime = myProcess.StartTime;                if ((DateTime.Now-startTime).Minutes>1)                {                    myProcess.Kill();                }            }        }        protected override void OnStop()        {        }    }}

 上邊的服務出現不穩定問題,運行一段時間以後就會,自動殺死Excel進程,不再計算Excel啟動時間與目前時間是否符合設定的時間差,還沒找到原因。

計時器不能穩定運行,最後使用了線程方式來定時,這次可以穩定的運行了

 

public partial class KillExcel : ServiceBase    {        private int _timeOut;        private Thread _t;        public KillExcel()        {            InitializeComponent();            int to;            int.TryParse(ConfigurationManager.AppSettings["TimeOut"], out to);            _timeOut = to > 0 ? to : 3;        }        protected override void OnStart(string[] args)        {            // TODO: 在此處添加代碼以啟動服務。            _t = new Thread(new ThreadStart(Monitor));            _t.IsBackground = true;            _t.Start();        }        private void Monitor()        {            int sleeptime = 60 * 1000 * _timeOut;            while (true)            {                Thread.Sleep(sleeptime);                killExcel();            }        }        public void killExcel()        {            Process[] myProcesses = Process.GetProcessesByName("Excel");            //得不到Excel進程ID,暫時只能判斷進程啟動時間            foreach (Process myProcess in myProcesses)            {                if ((DateTime.Now - myProcess.StartTime).Minutes > _timeOut)                {                    myProcess.Kill();                }            }            GC.Collect();        }        protected override void OnStop()        {                    }    }

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.