Capture Console Shutdown Event:
1.ctrl+c signal;
2.ctrl+break signal;
3. When the user system shuts down the console;
4. When the user exits the system;
5. When the system is going to close;
usingSystem;usingSystem.Runtime.InteropServices;usingSystem.Threading;usingSystem.Diagnostics;namespaceconsoleapplication2{ Public Delegate BOOLConsolectrldelegate (intDwctrltype); classProgram {[DllImport ("Kernel32.dll")] Private Static extern BOOLSetConsoleCtrlHandler (Consolectrldelegate Handlerroutine,BOOLadd); Private Const intCtrlcevent =0;//ctrl_c_event = 0;//A CTRL + C signal is received, the signal is either from the keyboard, or from the Generateconsolectrlevent function Private Const intCtrlbreakevent =1;//ctrl_break_event = 1;//a ctrl+break signal is received, either from the keyboard or from the Generateconsolectrlevent function Private Const intCtrlcloseevent =2;//ctrl_close_event = 2;//When the user system shuts down the console, the system sends this signal to this Private Const intCtrllogoffevent =5;//ctrl_logoff_event = 5;//the system sends this signal to all console programs when the user exits the system. The signal does not indicate which user exited. Private Const intCtrlshutdownevent =6;//ctrl_shutdown_event = 6;//this signal is sent to all console programs when the system is about to close[STAThread]Static voidMain (string[] args) { //TODO: Add code here to launch the applicationProgram CL =NewProgram (); } PublicProgram () {if(SetConsoleCtrlHandler (NewConsolectrldelegate (Handlerroutine),true) {Console.WriteLine ("Set SetConsoleCtrlHandler success!!"); } Else{Debug.WriteLine ("Set SetConsoleCtrlHandler error!!"); //Asreportfile.writefile ("", "test.txt", "who close?");} console.readline (); } BOOLHandlerroutine (intCtrltype) {Console.WriteLine ("Set SetConsoleCtrlHandler success!!"); Console.WriteLine ("Set SetConsoleCtrlHandler success!!"); Console.WriteLine ("Set SetConsoleCtrlHandler success!!"); Console.WriteLine ("Set SetConsoleCtrlHandler success!!"); Console.WriteLine ("Set SetConsoleCtrlHandler success!!"); Console.WriteLine ("Set SetConsoleCtrlHandler success!!"); Console.WriteLine ("Set SetConsoleCtrlHandler success!!"); Switch(ctrltype) { CaseCtrlCEvent:System.Console.WriteLine ("Ctrl + C KeyDown"); Break; CaseCtrlBreakEvent:System.Console.WriteLine ("Ctrl+break KeyDown"); Break; CaseCtrlCloseEvent:System.Console.WriteLine ("window closed"); Break; CaseCtrlLogoffEvent:System.Console.WriteLine ("Log off or shut down"); Break; CaseCtrlShutdownEvent:System.Console.WriteLine ("system shut down"); Break; default: System.Console.WriteLine (Ctrltype.tostring ()); Break; } for(inti =0; I <Ten; i++) {Console.WriteLine ("I is:{0}", i); Thread.Sleep ( +); } return false; } }}
[No000090] C # Capture Console Shutdown Event and response cmd shortcut key