I tried to execute a function when closing the program it works when I do CTRL + C but when I close it with the "X" the function is not fully executed.
So I would like to know if you know why and if so how to fix the problem.
I tried to do what is mentioned on this page Capture console exit C#.
Thank you in advance for your answers.
static void Main(string[] args)
{
_handler += new EventHandler(Handler);
SetConsoleCtrlHandler(_handler, true);
}
enum CtrlType
{
CTRL_C_EVENT = 0,
CTRL_BREAK_EVENT = 1,
CTRL_CLOSE_EVENT = 2,
CTRL_LOGOFF_EVENT = 5,
CTRL_SHUTDOWN_EVENT = 6
}
private static bool Handler(CtrlType sig)
{
example();
exitSystem = true;
Environment.Exit(-1);
return true;
}
public static bool exitSystem = false;
[DllImport("Kernel32")]
private static extern bool SetConsoleCtrlHandler(EventHandler handler, bool add);
private delegate bool EventHandler(CtrlType sig);
static EventHandler _handler;
public static void example()
{
for (int i = 0; i < 250000; i++)
Console.WriteLine(i);
}