C# 强制关闭当前程序进程(完全Kill掉不留痕迹)

C# 强制关闭当前程序进程(完全Kill掉不留痕迹)

C#代码  收藏代码
  1. /// <summary>  
  2.         /// 运行DOS命令  
  3.         /// DOS关闭进程命令(ntsd -c q -p PID )PID为进程的ID  
  4.         /// </summary>  
  5.         /// <param name="command"></param>  
  6.         /// <returns></returns>  
  7.         public static string RunCmd(string command)  
  8.         {  
  9.             //實例一個Process類,啟動一個獨立進程  
  10.             System.Diagnostics.Process p = new System.Diagnostics.Process();  
  11.   
  12.             //Process類有一個StartInfo屬性,這個是ProcessStartInfo類,包括了一些屬性和方法,下面我們用到了他的幾個屬性:  
  13.   
  14.             p.StartInfo.FileName = "cmd.exe";           //設定程序名  
  15.             p.StartInfo.Arguments = "/c " + command;    //設定程式執行參數  
  16.             p.StartInfo.UseShellExecute = false;        //關閉Shell的使用  
  17.             p.StartInfo.RedirectStandardInput = true;   //重定向標準輸入  
  18.             p.StartInfo.RedirectStandardOutput = true;  //重定向標準輸出  
  19.             p.StartInfo.RedirectStandardError = true;   //重定向錯誤輸出  
  20.             p.StartInfo.CreateNoWindow = true;          //設置不顯示窗口  
  21.   
  22.             p.Start();   //啟動  
  23.   
  24.             //p.StandardInput.WriteLine(command);       //也可以用這種方式輸入要執行的命令  
  25.             //p.StandardInput.WriteLine("exit");        //不過要記得加上Exit要不然下一行程式執行的時候會當機  
  26.   
  27.             return p.StandardOutput.ReadToEnd();        //從輸出流取得命令執行結果  
  28.   
  29.         }  

 在Program.cs加上如下

C#代码  收藏代码
  1. static class Program  
  2.     {  
  3.         /// <summary>  
  4.         /// 应用程序的主入口点。  
  5.         /// </summary>  
  6.         [STAThread]  
  7.         static void Main()  
  8.         {  
  9.             Application.EnableVisualStyles();  
  10.             Application.SetCompatibleTextRenderingDefault(false);  
  11.             Application.Run(new MainForm());  
  12.             //强制关闭进程  
  13.             string exeName = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;  
  14.             string[] exeArray = exeName.Split('\');  
  15.   
  16.             FunctionClass.RunCmd("taskkill /im " + exeArray[exeArray.Length-1] + " /f ");  
  17.         }  
  18.     }  
原文地址:https://www.cnblogs.com/gc2013/p/3829488.html