string processName = "notepad"; // 目標進程名稱
Process[] procs = Process.GetProcessesByName(processName);
if (procs.Length == 0) return;
Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.RedirectStandardError = true;
cmd.StartInfo.CreateNoWindow = true;
cmd.Start();
cmd.StandardInput.WriteLine($"ntsd -c q -p {procs[0].Id}");
cmd.StandardInput.WriteLine("exit");
cmd.WaitForExit();
原理:ntsd (Windows 偵錯工具) 以偵錯器身分附加進程並執行 q (quit) 命令,可終止普通 Kill() 無法結束的進程 (如系統關鍵進程、掛起進程)。
注意:需系統安裝 Debugging Tools for Windows (含 ntsd);Vista 以降版本可能需管理員權限。
string processName = "notepad";
Process[] procs = Process.GetProcessesByName(processName);
foreach (var p in procs)
{
try { p.Kill(); }
catch (Exception ex) { /* 記錄日誌: 權限不足、進程已結束等 */ }
}
優點:無外部依賴、程式碼簡單、.NET 內建。
缺點:受保護進程、關鍵系統進程、權限不足時會拋出例外。
// 嘗試優雅關閉 (僅適用有視窗的進程)
foreach (var p in procs)
{
if (p.CloseMainWindow())
{
if (!p.WaitForExit(3000)) // 等待 3 秒
p.Kill(); // 強制終止
}
else
{
p.Kill(); // 無主視窗直接強制
}
}
public static string RunCmd(string command, int timeoutMs = 5000)
{
using (Process p = new Process())
{
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = $"/c {command}";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;
p.Start();
string output = p.StandardOutput.ReadToEnd();
string error = p.StandardError.ReadToEnd();
p.WaitForExit(timeoutMs);
return output + error;
}
}
// 使用範例
string result = RunCmd("ipconfig /flushdns");
CloseMainWindow() → Kill()。ntsd (需部署偵錯工具) 或要求使用者手動結束。Process.StartInfo.Arguments="/c command" 模式,比重導向 StandardInput 更簡潔。