syloc
syloc

Reputation: 4709

How to kill a process started by cmd.exe

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?

Upvotes: 3

Views: 7400

Answers (3)

Michael
Michael

Reputation: 891

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.
                }
            }
            }

Upvotes: 10

Evgeny Lukashevich
Evgeny Lukashevich

Reputation: 1517

Well from command line you can use

taskkill /MI cmd.exe /T

Upvotes: 0

Ryan
Ryan

Reputation: 28187

Have you considered starting notepad.exe directly rather than using cmd.exe ?

Upvotes: 0

Related Questions