覆盖控制台关闭

时间:2009-02-10 07:07:25

标签: c# console override

我知道GUI已经

private void Form1_Closing(object sender, System.ComponentModel.EventArgs e)
{
  //do stuff
}
但是我如何在控制台应用程序中执行相同的操作?

C#/。NET3.5

1 个答案:

答案 0 :(得分:5)

以下是:

// Declare the SetConsoleCtrlHandler function
// as external and receiving a delegate.
[DllImport("Kernel32")]
public static extern bool SetConsoleCtrlHandler(HandlerRoutine Handler, bool Add);

// A delegate type to be used as the handler routine
// for SetConsoleCtrlHandler.
public delegate bool HandlerRoutine(CtrlTypes CtrlType);

// An enumerated type for the control messages
// sent to the handler routine.
public enum CtrlTypes
{
    CTRL_C_EVENT = 0,
    CTRL_BREAK_EVENT,
    CTRL_CLOSE_EVENT,
    CTRL_LOGOFF_EVENT = 5,
    CTRL_SHUTDOWN_EVENT
}

private static bool ConsoleCtrlCheck(CtrlTypes ctrlType)
{
    // Put your own handler here
    return true;
}

...

SetConsoleCtrlHandler(new HandlerRoutine(ConsoleCtrlCheck), true);