Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect when console is being closed?

Tags:

c#

.net

console

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?


1 Answers

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!

http://social.msdn.microsoft.com/Forums/en/windowscompatibility/thread/abf09824-4e4c-4f2c-ae1e-5981f06c9c6e

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.

like image 163
Nicholas Carey Avatar answered Jun 03 '26 17:06

Nicholas Carey