首页 > 解决方案 > 如何在 C# 控制台应用程序中使用多个 Ctrl+C 输入并用户确认以终止应用程序

问题描述

我想在用户多次确认后终止控制台应用程序。如果用户输入“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);
                }

            }

        }
    }
}```

标签: c#.net-coreconsoleconsole-application

解决方案


您尝试做的事情基本上超出了控制台的正常范围。它是 GUI 的领域,如 Windows 窗体和 WPF。具有事件队列的事物。并且您不会通过长时间运行的操作阻塞主/唯一线程。当然,您可以将事件队列改装到控制台。在控制台中,很容易复制所有其他环境程序流进行测试。

话虽如此,如果你有一个很长的循环,你可以通过使用 KeyAvalible 来查看 Inputs 而不会阻塞 Progression,如下所述:

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


推荐阅读