It turns out there is some Windows API trickery for this situation.
See the response by Willy Denoyette in
http://groups.google.com/group/microsoft.public.dotnet.languages.csharp/tree/browse_frm/thread/c72efe6c358eca9e/588a7bf4cfb4832[
^]
using System;
using System.Runtime.InteropServices;
using System.Threading;
namespace DetectNaughtyUser {
class Program {
public enum CtrlType {
CTRL_C_EVENT = 0,
CTRL_BREAK_EVENT = 1,
CTRL_CLOSE_EVENT = 2,
CTRL_LOGOFF_EVENT = 5,
CTRL_SHUTDOWN_EVENT = 6
}
public delegate Boolean HandlerRoutine(CtrlType sig);
[DllImport("kernel32.dll", EntryPoint = "SetConsoleCtrlHandler", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern Boolean SetConsoleCtrlHandler(
HandlerRoutine handlerRoutine,
[MarshalAs(UnmanagedType.Bool)] Boolean add);
private static Boolean Handler(CtrlType sig) {
Console.WriteLine("CtrlHandler {0}", sig);
if (sig == CtrlType.CTRL_CLOSE_EVENT) {
Console.WriteLine("Performing cleanup, please wait...");
Thread.Sleep(2000);
}
return false;
}
static void Main() {
SetConsoleCtrlHandler(Handler, true);
Console.WriteLine("Click the Close button {X] or Press Enter to end...");
Console.ReadLine();
}
}
}
It's advisable to make the "cleanup" quiet, as there is a warning on MSDN that console functions called from the handler may not work properly.
HandlerRoutine[
^]
SetConsoleCtrlHandler[
^]
Alan.