[英]How to kill a process started by cmd.exe
I'm trying to stop a process started by cmd.exe in c#. 我正在尝试停止c#中cmd.exe启动的进程。 For example start notepad with;
例如,开始记事本; cmd.exe /c notepad.
cmd.exe / c记事本。
System.Diagnostics.ProcessStartInfo("cmd.exe", "/c notepad");
When i kill the process the cmd.exe stops. 当我终止进程时,cmd.exe停止。 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 您应该使用自定义方法列出将cmd作为父进程的所有进程
You need to add System.Management reference first. 您需要先添加System.Management引用。
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.
}
}
}
您是否考虑过直接启动notepad.exe
而不是使用cmd.exe
?
Well from command line you can use 从命令行你可以使用
taskkill /MI cmd.exe /T
taskkill / MI cmd.exe / T.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.