Kill child process when parent process is killed

前端 未结 15 2640
轻奢々
轻奢々 2020-11-22 05:59

I\'m creating new processes using System.Diagnostics.Process class from my application.

I want this processes to be killed when/if my application has cr

15条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 06:45

    Just my 2018 version. Use it aside your Main() method.

        using System.Management;
        using System.Diagnostics;
    
        ...
    
        // Called when the Main Window is closed
        protected override void OnClosed(EventArgs EventArgs)
        {
            string query = "Select * From Win32_Process Where ParentProcessId = " + Process.GetCurrentProcess().Id;
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
            ManagementObjectCollection processList = searcher.Get();
            foreach (var obj in processList)
            {
                object data = obj.Properties["processid"].Value;
                if (data != null)
                {
                    // retrieve the process
                    var childId = Convert.ToInt32(data);
                    var childProcess = Process.GetProcessById(childId);
    
                    // ensure the current process is still live
                    if (childProcess != null) childProcess.Kill();
                }
            }
            Environment.Exit(0);
        }
    

提交回复
热议问题