最近要做个控制台程序,在用户关闭程序的时候要做些处理,但控制台程序却没有WinForm的Closing或Closed事件,想想只能用API才捕捉消息来实现了,代码如下:
1using System;
2using System.Windows.Forms;
3using System.Diagnostics;
4using System.Runtime.InteropServices;
5
6namespace ConsoleColsed
7{
8
9public delegate bool ConsoleCtrlDelegate(int dwCtrlType);
10
11public class ClsMain
12{
13 [DllImport("kernel32.dll")]
14 private static extern bool SetConsoleCtrlHandler(ConsoleCtrlDelegate HandlerRoutine,bool Add);
15 //当用户关闭Console时,系统会发送次消息
16 private const int CTRL_CLOSE_EVENT = 2;
17
18 [STAThread]
19 static void Main()
20 {
21 ClsMain cls=new ClsMain();
22 }
23
24 public ClsMain()
25 {
26 // 用API安装事件处理
27 ConsoleCtrlDelegate newDelegate=new ConsoleCtrlDelegate(HandlerRoutine);
28 bool bRet=SetConsoleCtrlHandler(newDelegate,true);
29 if(bRet==false) //安装事件处理失败
30 {
31 Debug.WriteLine("失败");
32 }
33 else
34 {
35 Console.WriteLine("ok");
36 Console.Read();
37 }
38 }
39 /// <summary>
40 /// 处理消息的事件
41 /// </summary>
42 private static bool HandlerRoutine(int CtrlType)
43 {
44 switch(CtrlType)
45 {
46 case CTRL_CLOSE_EVENT: //用户要关闭Console了
47 Debug.WriteLine("Close");
48 break;
49 }
50
51 return false;
52 }
53}
54}
55
2using System.Windows.Forms;
3using System.Diagnostics;
4using System.Runtime.InteropServices;
5
6namespace ConsoleColsed
7{
8
9public delegate bool ConsoleCtrlDelegate(int dwCtrlType);
10
11public class ClsMain
12{
13 [DllImport("kernel32.dll")]
14 private static extern bool SetConsoleCtrlHandler(ConsoleCtrlDelegate HandlerRoutine,bool Add);
15 //当用户关闭Console时,系统会发送次消息
16 private const int CTRL_CLOSE_EVENT = 2;
17
18 [STAThread]
19 static void Main()
20 {
21 ClsMain cls=new ClsMain();
22 }
23
24 public ClsMain()
25 {
26 // 用API安装事件处理
27 ConsoleCtrlDelegate newDelegate=new ConsoleCtrlDelegate(HandlerRoutine);
28 bool bRet=SetConsoleCtrlHandler(newDelegate,true);
29 if(bRet==false) //安装事件处理失败
30 {
31 Debug.WriteLine("失败");
32 }
33 else
34 {
35 Console.WriteLine("ok");
36 Console.Read();
37 }
38 }
39 /// <summary>
40 /// 处理消息的事件
41 /// </summary>
42 private static bool HandlerRoutine(int CtrlType)
43 {
44 switch(CtrlType)
45 {
46 case CTRL_CLOSE_EVENT: //用户要关闭Console了
47 Debug.WriteLine("Close");
48 break;
49 }
50
51 return false;
52 }
53}
54}
55