I have the following simple code:
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Process pr = Process.GetCurrentProcess();
pr.EnableRaisingEvents = true;
pr.Exited += HandleClosed;
Console.ReadKey();
}
private static void HandleClosed(object sender, EventArgs e)
{
File.Create(@"C:\MYDIR\myfile.c");
}
}
}
where when the console app exited I want to create the file specified in the HandleClosed
event. However the event Exited
is never raised even if I specified EnableRaisingEvents
to true
.
Any suggestion?
P.S. MSDN says:
The Exited event indicates that the associated process exited. This occurrence means either that the process terminated (aborted) or successfully closed. This event can occur only if the value of the EnableRaisingEvents property is true.
There are two ways of being notified when the associated process exits: synchronously and asynchronously. Synchronous notification means calling the WaitForExit method to block the current thread until the process exits. Asynchronous notification uses the Exited event, which allows the calling thread to continue execution in the meantime. In the latter case, EnableRaisingEvents must be set to true for the calling application to receive the Exited event.
When the operating system shuts down a process, it notifies all other processes that have registered handlers for the Exited event. At this time, the handle of the process that just exited can be used to access some properties such as ExitTime and HasExited that the operating system maintains until it releases that handle completely.
so it seems possible to detect that event even if the app is exited!