user34537
user34537

Reputation:

Detect when console is being closed?

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

Answers (1)

Nicholas Carey
Nicholas Carey

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!

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.

Upvotes: 9

Related Questions