Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

console application close

338 views
Skip to first unread message

Jim Heavey

unread,
Jul 13, 2005, 8:59:01 PM7/13/05
to
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!!!

Dave

unread,
Jul 13, 2005, 10:12:35 PM7/13/05
to
There is an event that you can bind to which will let you perform tear-down operations, although explicitly disposing of a managed
object may be useless as the framework will ensure proper clean-up when the appdomain is unloaded anyway. If your using unmanaged
file handles (or if you just want to be 100% sure that the memory is cleaned), then try binding to the event:

System.Diagnostics.Process process = System.Diagnostics.Process.GetCurrentProcess();
process.Exited += new EventHandler(OnExited);

// Note, you may also want to dispose of the "process" object when the event is fired.

--
Dave Sexton
dave@www..jwaonline..com
-----------------------------------------------------------------------
"Jim Heavey" <JimH...@discussions.microsoft.com> wrote in message news:5A1EF80F-3DD8-4E5F...@microsoft.com...

Willy Denoyette [MVP]

unread,
Jul 14, 2005, 3:34:04 AM7/14/05
to

"Jim Heavey" <JimH...@discussions.microsoft.com> wrote in message
news:5A1EF80F-3DD8-4E5F...@microsoft.com...

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.


0 new messages