Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override Console Close

I know the GUI has

private void Form1_Closing(object sender, System.ComponentModel.EventArgs e)
{
  //do stuff
}
But how can i do the same thing in a console application?

C#/.NET3.5

like image 336
Dacto Avatar asked Jun 28 '26 18:06

Dacto


1 Answers

Here's how:

// 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);
like image 62
Anton Gogolev Avatar answered Jun 30 '26 06:06

Anton Gogolev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!