The C # WIN32 console application ignores Ctrl + C and prevents the program from exiting, using the Windows API SetConsoleCtrlHandler function
Note: When debugging execution in VS, breakpoints are set in the handler routines and are not interrupted; prompt: No sources available, such as:
Complete Sample code:
Using system;using system.collections.generic;using system.text;using system.diagnostics;using System.runtime.interopservices;using system.threading;/******************************************************** * CSHARP_WIN32 Console Application ignores Ctrl + C * Powered by:testcs_dn * blog:http://www.php.cn/*//***************** /namespace Csharp_win32 Console Application ignores ctrlc{//define handler delegate public delegate bool Consolectrldelegate (int ctrltype); Class Program {//import Setctrlhandlerhandler API [DllImport ("Kernel32.dll")] private static extern bo Ol SetConsoleCtrlHandler (consolectrldelegate handlerroutine, bool Add); When the user shuts down the console, the system sends a second message, Private const int ctrl_close_event = 2; CTRL + C, the system sends the second message Private Const int ctrl_c_event = 0; Ctrl+break, the system sends the second message Private Const int ctrl_break_event = 1; The user exits (Unregisters) and the system sends a message to the private const int ctrl_logoff_event = 5; System offClosed, the system sends the message Private Const int ctrl_shutdown_event = 6; static void Main (string[] args) {Program CLS = new Program (); Console.readkey (); } public Program () {consolectrldelegate consoledelegete = new Consolectrldelegate (handlerroutine ); BOOL BRet = SetConsoleCtrlHandler (Consoledelegete, true); if (BRet = = false)//install event handling failed {Console.WriteLine ("Error"); while (true) {Console.WriteLine ("..."); Thread.Sleep (1000); }} else {Console.WriteLine ("OK"); while (true) {Console.WriteLine ("..."); Thread.Sleep (1000); }}}///<summary>///handler routines, where you write handler code for the specified event///Note: When debugging execution in VS, the breakpoint is set here, but not interrupt; prompt: no source available;///</summary>//<param name= "Ctrltype" ></param>///<returns></returns> pri vate static bool Handlerroutine (int ctrltype) {switch (ctrltype) {case Ctrl_c _event:console.writeline ("C"); return true; This returns true, which means that the response system is prevented from//break the operation of the program; Case CTRL_BREAK_EVENT:Console.WriteLine ("break"); Break Case CTRL_CLOSE_EVENT:Console.WriteLine ("CLOSE"); Break Case CTRL_LOGOFF_EVENT:Console.WriteLine ("LOGOFF"); Break Case CTRL_SHUTDOWN_EVENT:Console.WriteLine ("SHUTDOWN"); Break //return true;//indicates that the response system is blocked from the operation of the program return false;//ignore processing, let the system do the default action}}}