【发布时间】:2019-12-21 13:30:55
【问题描述】:
我想在用户多次确认后终止控制台应用程序。如果用户输入“y”,那么应用程序应该终止,否则它应该主动接受 Ctrl+C 输入事件,直到用户输入“y”。 使用此代码,用户只能输入一次 Ctrl+C,之后如果输入“y”以外的值,则不会再次将 Ctrl+C 作为输入。
using System.Threading;
namespace TerminateProgram
{
class Program
{
public static ManualResetEvent mre;
public static bool exitCode = false;
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
//Console.CancelKeyPress += new ConsoleCancelEventHandler(cancelHandler);
//Setup and start timer...
mre = new ManualResetEvent(false);
Console.CancelKeyPress += new ConsoleCancelEventHandler(cancelHandler);
//The main thread can just wait on the wait handle, which basically puts it into a "sleep" state
//and blocks it forever
mre.WaitOne();
Console.WriteLine("exiting the app");
Thread.Sleep(1000);
}
//this method will handle the Ctrl+C event and will ask for confirmation
public static void cancelHandler(object sender, ConsoleCancelEventArgs e)
{
var isCtrlC = e.SpecialKey == ConsoleSpecialKey.ControlC;
if (isCtrlC)
{
string confirmation = null;
Console.Write("Are you sure you want to cancel the task? (y/n)");
confirmation = Console.ReadLine();
if (confirmation.Equals("y", StringComparison.OrdinalIgnoreCase))
{
e.Cancel = true;
exitCode = true;
mre.Set();
}
else
{
Console.CancelKeyPress += new ConsoleCancelEventHandler(cancelHandler);
}
}
}
}
}```
【问题讨论】:
-
为什么用 ASP.Net 来标记它?这显然不是 ASP.Net 问题。
-
我已经修改了问题的标签。我不小心放了那个标签。
标签: c# .net-core console console-application