Reputation:
I googled and found Console.CancelKeyPress
which is useful and all but many times i close my console by closing the window. Using the X on the top right corner. Console.CancelKeyPress
detects ctrl+c, how do i detect closing via clicking the X?
Upvotes: 2
Views: 7779
Reputation: 74375
Try this:
class Program
{
static void Main( string[] args )
{
AppDomain.CurrentDomain.ProcessExit += ProcessExitHandler ;
}
static void ProcessExitHandler( object sender , EventArgs e )
{
throw new NotImplementedException("You can't shut me down. I quit!" ) ;
}
}
Edited to note: apparently, that and most other techniques are gone WRT console apps in Windows 7. The console app is forcibly terminated when the window is closed, so the app never gets signaled. Thx MS!
The solution seems to be (see above URL) to make your console app a windows app with an invisible window that handles the message WM_ENDSESSION
, which handler will get 5 seconds to terminate before being shutdown.
Upvotes: 9