我有一个控制台应用程序。我希望它开始一个过程并在该过程结束时结束。如果用户点击 ctrl + c,我不希望应用程序关闭。如果我设置 UseShellExecute = false,那么这正是我所期望的 - Ctrl C 被忽略。
但似乎在UseShellExecute:true时,ctrl+c事件传播到子进程,即使父进程取消也关闭子进程。
我不能 UseShellExecute:true 因为我想捕获控制台输出和控制台错误事件。
当 UseShellExecute:false 时,如何阻止 ctrl+c 事件到达子进程?
public static int Main(string[] args)
{
Console.CancelKeyPress += ConsoleOnCancelKeyPress;
Process process = new Process()
{
StartInfo = new ProcessStartInfo()
{
FileName = filename,
Arguments = args,
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardOutput = true,
RedirectStandardInput = true,
CreateNoWindow = false,
}
};
process.OutputDataReceived += process_OutputDataReceived;
process.ErrorDataReceived += process_ErrorDataReceived;
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
return -1;
}
private static void ConsoleOnCancelKeyPress(object sender, ConsoleCancelEventArgs consoleCancelEventArgs)
{
consoleCancelEventArgs.Cancel = true;
}