Sometimes the console (console) application that is developed internally by the company runs on the server and automatically shuts down because it encounters certain exceptions, which requires a mechanism to capture the console shutdown event and write the log for ease of maintenance and debugging.
The source code is as follows:
Program code
Code
1using System;
2using System.Runtime.InteropServices;
3using System.Threading;
4using System.Diagnostics;
5
6namespace Xmlpusher
7{
8 public delegate bool Consolectrldelegate (int dwctrltype);
9/**////<summary>
Summary of
///Class1.
///</summary>
class Class1
13 {
//the setconsolectrlhandler function Adds or removes an application-defined handlerroutine function
//from The list of handler functions for the calling process.
[DllImport ("kernel32.dll")]
The private static extern bool SetConsoleCtrlHandler (consolectrldelegate handlerroutine, bool Add);
18//A CTRL + C signal is received, either from the keyboard or from the Generateconsolectrlevent function
Private Const int ctrl_c_event = 0;
20//a Ctrl + Break signal is received, either from the keyboard or from the Generateconsolectrlevent function
Private Const int ctrl_break_event = 1;
22//When the user system closes the console, the system sends this signal to this
Private Const int ctrl_close_event = 2;
24//When a user exits the system the system will send this signal to all console programs. The signal does not show which user exited.
Private Const int ctrl_logoff_event = 5;
26//When the system will turn off to send this signal to all console programs
Private Const int ctrl_shutdown_event = 6;
/**////<summary>
29///The main entry point of the application.
///</summary>
[STAThread]
static void Main (string[] args)
33 {
34//
//TODO: Add code here to start the application
36//
Notoginseng CLASS1 cl = new Class1 ();
38}
39
public Class1 ()
41 {
consolectrldelegate newdategate = new Consolectrldelegate (handlerroutine);
-bool re = SetConsoleCtrlHandler (Newdategate, true);
-if (re)
45 {
Console.WriteLine ("Set SetConsoleCtrlHandler success!!");
47}
/Else
49 {
Debug.WriteLine ("Set setconsolectrlhandler error!!");
Wuyi Asreportfile.writefile ("", "test.txt", "who close?");
52}
Console.ReadLine ();
54}
55
bool Handlerroutine (int ctrltype)
57 {
switch (ctrltype)
59 {
Case Ctrl_close_event:
for (int i = 0; i < i++)
62 {
Console.WriteLine ("I is:{0}", i);
Thread.Sleep (1000);
65}
break;
67}
return false;
69}
70}
71}
72
73