views:

5029

answers:

2

I would like to be able to trap ctrl-c in a C# console application so that I can carry out some cleanups before exiting. What is the best way of doing this?

+10  A: 

See MSDN:

Console.CancelKeyPress Event

Article with code samples:

Ctrl-C and the .NET console application

aku
Actually, that article recommends P/Invoke, and `CancelKeyPress` is mentioned only briefly in the comments. A good article is http://www.codeneverwritten.com/2006/10/ctrl-c-and-net-console-application.html
bzlm
+15  A: 

The Console.CancelKeyPress event is used for this. This is how it's used:

public static void Main(string[] args)
{
 Console.CancelKeyPress += delegate {
  // call methods to clean up
 };

 while (true) {}
}

When the user presses Ctrl + C the code in the delegate is run and the program exits. This allows you to perform cleanup by calling necessairy methods. Note that no code after the delegate is executed.

There are other situations where this won't cut it. For example, if the program is currently performing important calculations that can't be immediately stopped. In that case, the correct strategy might be to tell the program to exit after the calculation is complete. The following code gives an example of how this can be implemented:

class MainClass
{
 private static bool keepRunning = true;

 public static void Main(string[] args)
 {
  Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs e) {
   e.Cancel = true;
   MainClass.keepRunning = false;
  };

  while (MainClass.keepRunning) {}
  Console.WriteLine("exited gracefully");
 }
}

The difference between this code and the first example is that e.Cancel is set to true, which means the execution continues after the delegate. If run, the program waits for the user to press Ctrl + C. When that happens the keepRunning varible changes value which causes the while loop to exit. This is a way to make the program exit gracefully.

Jonas