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?
Asked
Active
Viewed 7,236 times
1
-
1There's lots of help available [at this link](https://www.google.com/#q=detect+when+console+is+being+closed). – Robert Harvey Aug 24 '12 at 23:36
-
[Detecting Process Exit From Console Application in C#](http://geekswithblogs.net/mrnat/archive/2004/09/23/11594.aspx) – Omar Aug 24 '12 at 23:39
-
See http://stackoverflow.com/questions/11959643/why-does-closing-a-console-that-was-started-with-allocconsole-cause-my-whole-app and http://stackoverflow.com/questions/474679/capture-console-exit-c-sharp and other questions linked to from them. – Jon Hanna Aug 24 '12 at 23:46
1 Answers
7
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.

walther
- 13,466
- 5
- 41
- 67

Nicholas Carey
- 71,308
- 16
- 93
- 135
-
2@acidzombie24: apparently, Windows 7 and Vista broke...err...improved things. See my edited answer for details. – Nicholas Carey Aug 25 '12 at 00:49