I am writing a Console app in C# 4 and want to gracefully cancel my program and Ctrl + C is pressed. The following code I have used many times before, but now when trying to use it in .NET 4, it seems a strange unhandled exception is occurring.
namespace ConsoleTest
{
class Program
{
private static bool stop = false;
static void Main(string[] args)
{
System.Console.TreatControlCAsInput = false;
System.Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
while (!stop)
{
System.Console.WriteLine("waiting...");
System.Threading.Thread.Sleep(1000);
}
System.Console.WriteLine("Press any key to exit...");
System.Console.ReadKey(true);
}
static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
stop = true;
e.Cancel = true;
}
}
}
If I change the Target Framework to .NET 3.5, it works.
EDIT: It seems this person is seeing the same issue: http://johnwheatley.wordpress.com/2010/04/14/net-4-control-c-event-handler-broken/