退出或结束其他可执行文件

我有这个代码来运行exe:

String cPath = "C:\\GCOS\\HHT\\EXE\\" + frmSchemas.schema; string cParams = HHTNUMBER+" "+ Login.user + "/" + Login.pass + "//" +Login.db + "//" + frmSchemas.schema ; string filename = Path.Combine(cPath,"HHTCtrlp.exe"); Process.Start(filename, cParams); 

现在我如何结束上面的程序?

  Process[] processes = Process.GetProcessesByName("HHTCtrlp"); foreach (var process in processes) { process.Kill(); } 

以下是来自http://csharp-slackers.blogspot.com/2008/09/terminate-process.html的示例

 using System; using System.Threading; using System.Diagnostics; public class TerminateProcessExample { public static void Main () { // Create a new Process and run notepad.exe. using (Process process = Process.Start("notepad.exe")) { // Wait for 5 seconds and terminate the notepad process. Console.WriteLine("Waiting 5 seconds before terminating" + " notepad.exe."); Thread.Sleep(5000); // Terminate notepad process. Console.WriteLine("Terminating Notepad with CloseMainWindow."); // Try to send a close message to the main window. if (!process.CloseMainWindow()) { // Close message did not get sent - Kill Notepad. Console.WriteLine("CloseMainWindow returned false - " + " terminating Notepad with Kill."); process.Kill(); } else { // Close message sent successfully; wait for 2 seconds // for termination confirmation before resorting to Kill. if (!process.WaitForExit(2000)) { Console.WriteLine("CloseMainWindow failed to" + " terminate - terminating Notepad with Kill."); process.Kill(); } } } // Wait to continue. Console.WriteLine("Main method complete. Press Enter."); Console.ReadLine(); } } 

正如您所看到的,除了使用Process.Kill();之外,还有更多优雅的方法来尝试终止进程Process.Kill();

Process.Start将返回一个Process实例。 您可以在实例上调用Kill来终止进程。

你可以保持你开始的过程:

 var example_process = Process.Start("notepad.exe"); 

然后:

 example_process.Kill(); 
 Process p = Process.Start(filename, cParams); ... p.Kill(); 
 Process proc = Process.Start(filename, cParams); // .... proc.CloseMainWindow(); proc.Close(); // ...or the rude way ;) ... proc.Kill(); 

保持进程的句柄 – Process.Start返回一个Process对象。

然后你可以使用(在极端情况下):

 process.Kill(); 

阻止它。

使用:

 process.CloseMainWindow(); 

可能是一种更好的方法(假设该过程具有UI)

您需要进程ID才能将其终止。

 foreach (Process proc in Process.GetProcesses()) { if (proc.Id == _processID) { proc.Kill(); } } 

将您的流程分配给变量并调用Kill方法。 即

 String cPath = "C:\\GCOS\\HHT\\EXE\\" + frmSchemas.schema; string cParams = HHTNUMBER+" "+ Login.user + "/" + Login.pass + "//" +Login.db + "//" + frmSchemas.schema ; string filename = Path.Combine(cPath,"HHTCtrlp.exe"); var p = Process.Start(filename, cParams); // ... Later in Code ... p.Kill(); 
 System.Diagnostics.Process.Start("c:\\windows\\system32\\notepad.exe"); System.Diagnostics.Process q; q = System.Diagnostics.Process.GetProcessesByName("notepad")[0]; q.Kill();