More tips from Sairama - Catching Ctrl-C from a .NET Console Application
Sponsored By
Ever want to catch Ctrl-C from a .NET Console Application and perform some crucial cleanup? Well, you can...
using
System;using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
namespace Testing
{
/// <summary>
/// Class to catch console control events (ie CTRL-C) in C#.
/// Calls SetConsoleCtrlHandler() in Win32 API
/// </summary>
public class ConsoleCtrl: IDisposable
{
/// <summary>
/// The event that occurred.
/// </summary>
public enum ConsoleEvent
{
CtrlC = 0,CtrlBreak = 1,CtrlClose = 2,CtrlLogoff = 5,CtrlShutdown = 6
} /// <summary>
/// Handler to be called when a console event occurs.
/// </summary>
public delegate void ControlEventHandler(ConsoleEvent consoleEvent); /// <summary>
/// Event fired when a console event occurs
/// </summary>
public event ControlEventHandler ControlEvent; ControlEventHandler eventHandler; public ConsoleCtrl()
{
// save this to a private var so the GC doesn't collect it...
eventHandler = new ControlEventHandler(Handler);
SetConsoleCtrlHandler(eventHandler, true);
}
~
ConsoleCtrl(){Dispose(false);} public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
} void Dispose(bool disposing)
{
if (eventHandler != null)
{
SetConsoleCtrlHandler(eventHandler, false);
eventHandler = null;
}
} private void Handler(ConsoleEvent consoleEvent)
{
if (ControlEvent != null)
ControlEvent(consoleEvent);
}
[
DllImport("kernel32.dll")]static extern bool SetConsoleCtrlHandler(ControlEventHandler e, bool add);
}
}
using
System;using System.Reflection;
using System.Diagnostics;
namespace .Testing
{
class Test
{
public static void inputHandler(ConsoleCtrl.ConsoleEvent consoleEvent)
{
if (consoleEvent == ConsoleCtrl.ConsoleEvent.CtrlC)
{
Console.WriteLine("Stopping due to user input");
// Cleanup code here.
System.Environment.Exit(-1);
}
} [STAThread]
static void Main(string[] args)
{ ConsoleCtrl cc = new ConsoleCtrl();
cc.ControlEvent += new ConsoleCtrl.ControlEventHandler(inputHandler);
for( ;; )
{
Console.WriteLine("Press any key...");
Console.ReadLine();
}
}
}
}
About Scott
Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.
About Newsletter
March 10, 2005 16:02
the codes work well, thank you!
Comments are closed.