c# - 如何在 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);
}
}
}
}
}```
解决方案
您尝试做的事情基本上超出了控制台的正常范围。它是 GUI 的领域,如 Windows 窗体和 WPF。具有事件队列的事物。并且您不会通过长时间运行的操作阻塞主/唯一线程。当然,您可以将事件队列改装到控制台。在控制台中,很容易复制所有其他环境程序流进行测试。
话虽如此,如果你有一个很长的循环,你可以通过使用 KeyAvalible 来查看 Inputs 而不会阻塞 Progression,如下所述:
推荐阅读
- python-3.x - 在函数调用期间使用锁进行多线程
- swift - 为什么图像没有从 Xcode 中的 Cloud Firestore 加载
- java - 使用 jOOQ 作为模式生成器(纯 sql 作为输出)
- wordpress - 如何覆盖 woocommerce_download_file_redirect 函数?
- excel - Sumifs或索引匹配?
- javascript - 如何创建具有给定键和值的对象?
- php - PhpOffice 将 excel 转换为 json
- java - 针对不同用户的设计模式
- api - 使用 GCP API 网关的 Graphql 后端的 OpenAPI 配置?
- google-apps-script - 有没有我可以创建的谷歌脚本,所以我的电子表格中的每一行都会复制到一个新的单独的工作表中?