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?
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.
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With