Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to kill a process started by cmd.exe

Tags:

c#

process

I'm trying to stop a process started by cmd.exe in c#. For example start notepad with; cmd.exe /c notepad.

System.Diagnostics.ProcessStartInfo("cmd.exe", "/c notepad");

When i kill the process the cmd.exe stops. But notepad remains. How can i get a handle for notepad and stop it?

like image 924
syloc Avatar asked May 17 '26 04:05

syloc


1 Answers

You should use a custom method to list all process that have cmd as parent process

You need to add System.Management reference first.

Then simply kill the process tree:

            void Main()
            {

                var psi = new ProcessStartInfo("cmd.exe", "/c notepad");
                var cmdProcess = Process.Start(psi);
                Thread.Sleep(2000);
                KillProcessAndChildren(cmdProcess.Id);

            }

            public void KillProcessAndChildren(int pid)
            {
            using (var searcher = new ManagementObjectSearcher
                ("Select * From Win32_Process Where ParentProcessID=" + pid))
            {
                var moc = searcher.Get();
                foreach (ManagementObject mo in moc)
                {
                    KillProcessAndChildren(Convert.ToInt32(mo["ProcessID"]));
                }
                try
                {
                    var proc = Process.GetProcessById(pid);
                    proc.Kill();
                }
                catch (Exception e)
                {
                    // Process already exited.
                }
            }
            }
like image 60
Michael Avatar answered May 19 '26 18:05

Michael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!