【问题标题】:How to take multiple Ctrl+C input in C# Console app with user confirmation to terminate the App如何在 C# 控制台应用程序中使用多个 Ctrl+C 输入并用户确认以终止应用程序
【发布时间】: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


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2013-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-15
    • 1970-01-01
    • 2017-10-17
    • 1970-01-01
    相关资源
    最近更新 更多