|
|
[楼主] C# windows控制台程序捕获Ctrl+C按键事件 /////////////////////////////////////// //由linux.j66.net整理,源代码来源于网络 //////////////////////////////////////// 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); } 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); } class Test { public static void inputHandler(ConsoleCtrl.ConsoleEvent consoleEvent) { if (consoleEvent == ConsoleCtrl.ConsoleEvent.CtrlC) { Console.WriteLine("Stopping due to user input"); System.Threading.Thread.Sleep(1000); 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(); } } } } |
|