用 kernel32.dll 中的 API
[DllImport("kernel32.dll")]
static extern bool SetConsoleCtrlHandler(HandlerRoutineCallback call, bool add);
delegate bool HandlerRoutineCallback(uint dwCtrlType);
const uint CTRL_CLOSE_EVENT = 2;
SetConsoleCtrlHandler(
delegate(uint type)
{
return (type == CTRL_CLOSE_EVENT);
}
, true);
不过有超时限制,两秒内如果没有处理完 Windows 会弹出对话框