"Jim Heavey" <Ji*******@discussions.microsoft.com> wrote in message
news:5A**********************************@microsof t.com...
When I run a console application by bringing up a dos window and then
running
the exe, I noticed that when I close the dos window, this kills my
application. My question is, Is there some way that I can detect this and
ensure that I can control how my application closes? I need to ensure
that
the disk file I have open that I properly close it before the application
goes away.
Thanks in advance for your assistance!!!
I would suggest you to install a Console Control handler that catches the
Console Close event.
enum CtrlType {
CTRL_C_EVENT = 0,
CTRL_BREAK_EVENT = 1,
CTRL_CLOSE_EVENT = 2,
CTRL_LOGOFF_EVENT = 5,
CTRL_SHUTDOWN_EVENT = 6
}
private delegate bool EventHandler(CtrlType sig);
// Sample Console CTRL handler
private static bool Handler(CtrlType sig)
{
bool handled = false;
switch (sig)
{
case CtrlType.CTRL_C_EVENT:
case CtrlType.CTRL_LOGOFF_EVENT:
case CtrlType.CTRL_SHUTDOWN_EVENT:
case CtrlType.CTRL_CLOSE_EVENT:
{
// Clean-up code goes here
}
// return false if you want the process to exit.
// returning true, causes the system to display a dialog
// giving the user the choice to terminate or continue
handled = true;
break;
default:
return handled;
}
return handled;
}
[DllImport("Kernel32")]
private static extern bool SetConsoleCtrlHandler (EventHandler handler,
bool add);
...in Main()...
// Install handler
_handler += new EventHandler(Handler);
SetConsoleCtrlHandler(_handler, true);
....
Willy.