Reputation: 46813
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.
Upvotes: 5
Views: 1180
Reputation: 7896
This should work...
Console.CancelKeyPress += new ConsoleCancelEventHandler((o, e) =>
{
Console.WriteLine("Control+C hit. Shutting down.");
Environment.Exit(0);
});
Console.ReadLine();
Upvotes: 2
Reputation: 57678
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);
}
Upvotes: 3
Reputation: 1099
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();
}
Upvotes: 0