On 2005-07-06, David Griffin <ca***********@ yahoo.com> wrote:
I have a console application that spawns off several C# threads. It
needs to react to shutdown of the system by performing some end of
program activities including writing some files and closing some other
open files and then shutting down gracefully.
I've done a lot of searching online and there seem to be a lot of
potentially interesting leads, an OnShutdown is mentioned, as is a
SessionEnding event, but I'm not sure what the normal procedure is. I
suspect I need to create an event delegate and then register for this
session ending event, but I'm not exactly sure how to do it and I was
hoping to find a code sample. Does anyone know where I can find one?
Thanks.
David W. Griffin
Lockheed Martin Aeronautics Company
*** Sent via Developersdex http://www.developersdex.com ***
As was mentioned, you need to use the win32 SetConsoleCtrlH andler api to
set up a callback. The code looks something like:
using System;
using System.Runtime. InteropServices ;
private enum ControlEventTyp e
{
CtrlCEvent = 0,
CtrlBreakEvent = 1,
CtrlCloseEvent = 2,
CtrlLogoffEvent = 5,
CtrlShutdownEve nt = 6,
}
private delegate bool HandlerDelegate (ControlEventTy pe dwControlType);
[DllImport ("kernel32", SetLastError=tr ue)]
private static extern bool SetConsoleCtrlH andler (
HandlerDelegate HandlerRoutine,
bool Add);
public class ConsoleApp
{
private static HandlerDelegate controlHandler;
public static void Main ()
{
// create the delegate and add the handler
controlHandler += new HandlerDelegate (ControlHandler );
SetConsoleCtrlH andler (controlHandler , true);
// do you cool stuff
// clean up...
SetConsoleCtrlH andler (controlHandler , false);
}
private static bool ControlHandler (ControlEventTy pe controlEvent)
{
// if you handle the signal, return true - else false
switch (controlEvent)
{
case ControlEventTyp e.CtrlCEvent:
....
break;
case ControlEventTyp e.CtrlShutdownE vent:
...
break;
...
}
}
}
Anyway, this is obviously untested air code - but I do have a working
sample somewhere, if you really need it I'll dig it out. I actually
have a class with most of the win32 console api calls in it :)
--
Tom Shelton [MVP]