1

I would like to know if there is a way that when you exit a console app pressing the X button, the program makes an action.

I know there is a way with Ctrl + C:

CancelKeyPress += new ConsoleCancelEventHandler(MyHandler);
while (true)
{
    //The program code...
}

protected static void MyHandler(object sender, ConsoleCancelEventArgs args)
{
    //Action
}

But I need one that work with the exit button or/and alt + F4.

Thanks for your time.

Lumito
  • 490
  • 6
  • 20

1 Answers1

0

You could register a Control Handler Function and handle the CTRL_CLOSE_EVENT. Here is an example to do so in C#, see Detecting console closing in .NET for more information and a nicer example:

[DllImport("Kernel32")]
private static extern bool SetConsoleCtrlHandler(HandlerRoutine handlerRoutine, bool add);
private delegate bool HandlerRoutine(int signal);

static void Main(string[] args)
{
    SetConsoleCtrlHandler(signal =>
    {
        if (signal == 2) // see https://learn.microsoft.com/en-us/windows/console/handlerroutine
        {
            // TODO: handle the close event
            return true;
        }
        return false;
    }, true);

    Console.ReadLine();
}
user7217806
  • 2,014
  • 2
  • 10
  • 12