C# 控制台应用程序:防止打印 Control-C?

发布于 2024-09-05 19:32:13 字数 410 浏览 10 评论 0原文

我有一个控制台应用程序,我想捕获 Control-C 并正常关闭。

我有以下代码:

Console.CancelKeyPress += new ConsoleCancelEventHandler((o, e) =>
{
   Logger.Log("Control+C hit. Shutting down.");
   resetEvent.Set();
});

输出窗口显示:

6/16/2010 3:24:34 PM:按 Control+C。正在关闭。
^C

有没有办法防止 control-c 字符 ^C 出现?这不是什么大事,但出于某种原因我会很关注它,因为我就是这样的肛门。

I have a console app, and I want to capture Control-C and shutdown gracefully.

I have the following code:

Console.CancelKeyPress += new ConsoleCancelEventHandler((o, e) =>
{
   Logger.Log("Control+C hit. Shutting down.");
   resetEvent.Set();
});

And the output windows shows:

6/16/2010 3:24:34 PM: Control+C hit. Shutting down.
^C

Is there a way to prevent the control-c character ^C from appearing? It's not a huge deal, but for some reason Ill be fixated on it because I'm anal like that.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

葮薆情 2024-09-12 19:32:13

作为控制台应用程序,我将使用 Environment.Exit 来表示应用程序正在退出,这样可以阻止 ^C 被打印。

您甚至可以提供特定的错误代码来表示用户按下了 CTRL+C

static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
    Console.WriteLine("Control+C hit. Shutting down."); 

    Environment.Exit(-1);
}

Being a console application I would use Environment.Exit to signal that the application is exiting and this way stopping the ^C from being print.

You could even provide a specific error code to symbolize that the user pressed CTRL+C.

static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
    Console.WriteLine("Control+C hit. Shutting down."); 

    Environment.Exit(-1);
}
不再让梦枯萎 2024-09-12 19:32:13

这应该有效...

Console.CancelKeyPress += new ConsoleCancelEventHandler((o, e) =>
{
    Console.WriteLine("Control+C hit. Shutting down.");
    Environment.Exit(0);
});

Console.ReadLine();

This should work...

Console.CancelKeyPress += new ConsoleCancelEventHandler((o, e) =>
{
    Console.WriteLine("Control+C hit. Shutting down.");
    Environment.Exit(0);
});

Console.ReadLine();
任谁 2024-09-12 19:32:13

虽然这不一定是您想要实现的解决方案,但它确实会阻止显示 ^C:

static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
    Console.WriteLine("Control+C hit. Shutting down.");     
    Process.GetCurrentProcess().Kill();
}

While this is not necessarily a solution you want to implement, it does prevent the ^C from being displayed:

static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
    Console.WriteLine("Control+C hit. Shutting down.");     
    Process.GetCurrentProcess().Kill();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文