简体   繁体   中英

How to take multiple Ctrl+C input in C# Console app with user confirmation to terminate the App

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);
                }

            }

        }
    }
}```

What you are trying to do in fundamentally out of normal reach for the console. It is the realm of GUI's like Windows Forms and WPF. Things that have a Event Queue. And where you do not block the Main/Only Thread with a long running operation. Of course you can retrofit a Event Queue to Console. In Console it is very easy to duplicate every other Environments Programm flow for testing.

That being said if you got a loop long, you can look at Inputs without blocking Progression, by using KeyAvalible as discussed here:

https://stackoverflow.com/a/5620647/3346583

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM