Saturday, June 6, 2015

Killing child process when parent software killed.

You need add using System.Management;

 
 /// 
           /// Kill a process, and all of its children, grandchildren, etc.
           /// 
           /// Process ID.
           private static void KillProcessAndChildren(int pid)
           {
               ManagementObjectSearcher searcher = new ManagementObjectSearcher
                 ("Select * From Win32_Process Where ParentProcessID=" + pid);
               ManagementObjectCollection moc = searcher.Get();
               foreach (ManagementObject mo in moc)
               {
                   KillProcessAndChildren(Convert.ToInt32(mo["ProcessID"]));
               }
               try
               {
                   Process proc = Process.GetProcessById(pid);
                   proc.Kill();
               }
               catch (ArgumentException)
               {
                   // Process already exited.
               }
           } 

Sample using it declare first, so we can access it everywhere

 private int idkita;
Button CLICK
private void button1_Click(object sender, EventArgs e)
           {

               ProcessStartInfo startInfo = new ProcessStartInfo();
               //startInfo.WindowStyle = ProcessWindowStyle.Hidden;
               Process ieProcess = Process.Start(@"notepad.exe", "");
               idkita = ieProcess.Id;
}
Add to form closing FORM CLOSING
  private void Form1_FormClosing(object sender, FormClosingEventArgs e)
           {
               KillProcessAndChildren(idkita);
           }