启动进程: private void StartProcess() { try { if (!CheckProcessExists()) { Process p = new Process(); p.StartInfo.FileName = System.IO.Path.Combine(Application.StartupPath, "DataTool.exe"); p.StartInfo.Arguments = "DataTool.exe"; p.StartInfo.UseShellExecute = true; p.Start(); p.WaitForInputIdle(10000); } } catch (Exception ex) { MessageBox.Show(ex.Source + " " + ex.Message); } } private bool CheckProcessExists() { Process[] processes = Process.GetProcessesByName("DataTool"); foreach (Process p in processes) { if (System.IO.Path.Combine(Application.StartupPath, "DataTool.exe") == p.MainModule.FileName) return true; } return false; } 结束进程: private void KillProcessExists() { Process[] processes = Process.GetProcessesByName("AppStart"); foreach (Process p in processes) { if (System.IO.Path.Combine(Application.StartupPath, "AppStart.exe") == p.MainModule.FileName) { p.Kill(); p.Close(); } } }
有时再写的客户端软件中,使用到比如Quartz.net 等定时作业调度组件时,
往往会出现自己的应用程序已经关闭了,但是进程还未结束,这时,需要在关闭窗口时的FormClosed事件里加上下面的代码:
private void MainForm_FormClosed(object sender, FormClosedEventArgs e) { Process current = Process.GetCurrentProcess(); Process[] processes = Process.GetProcessesByName(current.ProcessName); foreach (Process process in processes) { if (process.Id == current.Id) { process.Kill(); } } }
找到当前的应用程序进程,并结束他,就可以了。