I want to terminate the Console app upon multiple confirmation from User. If the user enters "y", then the app should terminate, else it should be actively taking the Ctrl+C input event, until the user enters "y". With this code, user is able to input Ctrl+C only once, after that Ctrl+C isn't taken as input again if he inputs value other than "y".
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);
}
}
}
}
}```