c# – Catch console program closing

Question:

There is a console application (C#), I need to catch the event of its closing. It can be Ctrl+C and clicking on the cross, in general, any event after which the program will close. How can this be done?

Answer:

Thanks to the commentators above, I will translate the content from the link.

My program uses an infinite loop. Firstly, we can insert a method at the end of the program, or we can, for everyone, add a trigger to the closing event with the combination ^C

class Program
{
    static int Main(string[] args)
    {
        // Добавляем слушатель события
        Console.CancelKeyPress += Console_CancelKeyPress;
        while ( true )
        {
            // Наш бесконечный цикл
        }
        Console_CancelKeyPress(); // Навсякий (пожарный) случай пихаем это сюды.
        return 0; Может быть сюда программа не придет, но не факт
    }
    // Без нужных, слушателю событий, аргументов
    static void Console_CancelKeyPress()
    {
        Console.WriteLine("Exiting");
        // Termitate what I have to terminate
        Environment.Exit(-1);
    }
    // Делаем перегрузку метода, чтобы наш слушатель событий не выдавал ошибку
    static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
    {
        Console_CancelKeyPress();
    }
}
Scroll to Top