console application close

G

Guest

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!!!
 
D

Dave

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.
 
W

Willy Denoyette [MVP]

Jim Heavey said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top