Application Scenarios
We develop a console application that is likely to be terminated by the user Ctrl + C at run time or closed directly by the user. If we do not want users to terminate our program via CTRL + C, we need to handle CTRL + C or shutdown events.
Processing methods
There is a cancelkeypress event in the console class under the. NET platform that handles CTRL + C, but there is nothing to do with directly shutting down the console application.
However, there is a SetConsoleCtrlHandler function in the Windows API that can handle both of these shutdown events.
C # handles the code as follows:
The code is as follows:
Static Class Program
{
Public delegate bool Controlctrldelegate (int ctrltype);
[DllImport ("kernel32.dll")]
private static extern bool SetConsoleCtrlHandler (controlctrldelegate handlerroutine, bool Add);
private static Controlctrldelegate Cancelhandler = new Controlctrldelegate (handlerroutine);
public static bool Handlerroutine (int ctrltype)
{
Switch (ctrltype)
{
Case 0:
Console.WriteLine ("0 tool is forced to close"); CTRL + C Close
Break
Case 2:
Console.WriteLine ("2 tool is forced to close");//Press the console Close button to close
Break
}
Console.ReadLine ();
return false;
}
<summary>
The main entry point for the application.
</summary>
[STAThread]
static void Main (string[] args)
{
SetConsoleCtrlHandler (Cancelhandler, true);
Console.ReadLine ();
}
}
In addition to the Declaration,
Running GuestArticles are original, reproduced please link to the form of the address of this article
Code instance that handles 2 shutdown events in a C # console program
This address: http://www.paobuke.com/develop/c-develop/pbk23468.html
Related content An analysis of the method of the current time of ASP. C # static class, static constructor, static variable C # webclient Chinese garbled problem solving method using C # to write a small program that calculates the ID number of a train ticket
How to use WinForm to implement a cool transparent animation interface in C # inline-asm solve embedded x86 assembler C # interface (Interface) usage Analysis C # method for generating code128 barcodes
Code instance that handles 2 shutdown events in a C # console program