I'll use process events to wire up a method that will print something when the console is exited. You can see that because I don't know which event to wire up, I used three that all sound like they would work.
To test this, use the code below. The console window will stay open for 5 seconds. Click the "x" in the top right to close the window prior to the 5 seconds. Expected is that the CurrentDomain_ProcessExit method will be called. It doesn't get called. What is the correct way of doing this using managed .net code? I would rather not use p/invoke etc.
public static void Main(string[] args)
{
var currentProcess = Process.GetCurrentProcess();
currentProcess.Exited += CurrentDomain_ProcessExit;
AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit;
AppDomain.CurrentDomain.DomainUnload += CurrentDomain_ProcessExit;
Thread.Sleep(5000);
}
internal static void CurrentDomain_ProcessExit(object sender, EventArgs e)
{
Console.WriteLine("we just captured the process exit."); // <-- this is never reached.
}