views:

283

answers:

2

I know the GUI has

private void Form1_Closing(object sender, System.ComponentModel.EventArgs e)
{
  //do stuff
}
But how can i do the same thing in a console application?

C#/.NET3.5

A: 

Add

Console.Readline()

at the and of the program, and de commandwindow will stay open until you press any key.

I'm not sure if that is what you need, 'cause you do'nt give very much info.

Natrium
+2  A: 

Here's how:

// Declare the SetConsoleCtrlHandler function
// as external and receiving a delegate.
[DllImport("Kernel32")]
public static extern bool SetConsoleCtrlHandler(HandlerRoutine Handler, bool Add);

// A delegate type to be used as the handler routine
// for SetConsoleCtrlHandler.
public delegate bool HandlerRoutine(CtrlTypes CtrlType);

// An enumerated type for the control messages
// sent to the handler routine.
public enum CtrlTypes
{
    CTRL_C_EVENT = 0,
    CTRL_BREAK_EVENT,
    CTRL_CLOSE_EVENT,
    CTRL_LOGOFF_EVENT = 5,
    CTRL_SHUTDOWN_EVENT
}

private static bool ConsoleCtrlCheck(CtrlTypes ctrlType)
{
    // Put your own handler here
    return true;
}

...

SetConsoleCtrlHandler(new HandlerRoutine(ConsoleCtrlCheck), true);
Anton Gogolev
Where can i read more about this? I dont fully understand how to use it.
Dacto
Read about P/Invoke (or PInvoke) on MSDN. Docs on SetConsoleCtrlHandler() are over there as well.
Anton Gogolev
Ok, so I have a little more of an understanding, but i still don't know how to block the CTRL_CLOSE_EVENT, ive tried returning false/true if it catches that event, but no success.
Dacto