[DllImport("kernel32.dll",SetLastError=true)]
[return: MarshalAs( UnmanagedType.Bool )]
static extern bool AllocConsole();
[DllImport("kernel32.dll",SetLastError=true)]
[return: MarshalAs( UnmanagedType.Bool )]
static extern bool FreeConsole();
// Delegate type to be used as the Handler Routine for SCCH
delegate bool ConsoleCtrlDelegate(CtrlTypes CtrlType);
// Enumerated type for the control messages sent to the handler routine
enum CtrlTypes: uint
{
CTRL_C_EVENT=0,
CTRL_BREAK_EVENT,
CTRL_CLOSE_EVENT,
CTRL_LOGOFF_EVENT=5,
CTRL_SHUTDOWN_EVENT
}
[DllImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetConsoleCtrlHandler(ConsoleCtrlDelegate HandlerRoutine, bool Add);
private static bool ctrlHandler(CtrlTypes CtrlType)
{
if ((CtrlType == CtrlTypes.CTRL_C_EVENT) || (CtrlType == CtrlTypes.CTRL_BREAK_EVENT))
{
FreeConsole();
return true;
}
if (CtrlType == CtrlTypes.CTRL_CLOSE_EVENT)
return true;
return false;
}