如何捕捉控制台程序的关闭事件。

最近要做个控制台程序,在用户关闭程序的时候要做些处理,但控制台程序却没有WinForm的Closing或Closed事件,想想只能用API才捕捉消息来实现了,代码如下:

 1 None.gif using  System;
 2 None.gif using  System.Windows.Forms;
 3 None.gif using  System.Diagnostics;
 4 None.gif using  System.Runtime.InteropServices;
 5 None.gif
 6 None.gif namespace  ConsoleColsed
 7 ExpandedBlockStart.gifContractedBlock.gif dot.gif {
 8InBlock.gif
 9InBlock.gifpublic delegate bool ConsoleCtrlDelegate(int dwCtrlType);
10InBlock.gif
11InBlock.gifpublic class ClsMain 
12ExpandedSubBlockStart.gifContractedSubBlock.gifdot.gif{  
13InBlock.gif [DllImport("kernel32.dll")]
14InBlock.gif private static extern bool SetConsoleCtrlHandler(ConsoleCtrlDelegate HandlerRoutine,bool Add);
15InBlock.gif //当用户关闭Console时,系统会发送次消息
16InBlock.gif private const int CTRL_CLOSE_EVENT = 2;
17InBlock.gif
18InBlock.gif [STAThread]
19InBlock.gif static void Main() 
20ExpandedSubBlockStart.gifContractedSubBlock.gif dot.gif{
21InBlock.gif  ClsMain cls=new ClsMain();      
22ExpandedSubBlockEnd.gif }

23InBlock.gif  
24InBlock.gif public ClsMain()
25ExpandedSubBlockStart.gifContractedSubBlock.gif dot.gif{
26InBlock.gif  // 用API安装事件处理
27InBlock.gif  ConsoleCtrlDelegate newDelegate=new ConsoleCtrlDelegate(HandlerRoutine);
28InBlock.gif               bool bRet=SetConsoleCtrlHandler(newDelegate,true);
29InBlock.gif  if(bRet==false)  //安装事件处理失败
30ExpandedSubBlockStart.gifContractedSubBlock.gif  dot.gif{
31InBlock.gif   Debug.WriteLine("失败");
32ExpandedSubBlockEnd.gif  }

33InBlock.gif  else
34ExpandedSubBlockStart.gifContractedSubBlock.gif  dot.gif{
35InBlock.gif   Console.WriteLine("ok");
36InBlock.gif   Console.Read();
37ExpandedSubBlockEnd.gif  }

38ExpandedSubBlockEnd.gif         }

39ExpandedSubBlockStart.gifContractedSubBlock.gif   /**//// <summary>
40InBlock.gif   /// 处理消息的事件
41ExpandedSubBlockEnd.gif   /// </summary>

42InBlock.gif   private static bool HandlerRoutine(int CtrlType)
43ExpandedSubBlockStart.gifContractedSubBlock.gif   dot.gif{
44InBlock.gif switch(CtrlType)
45ExpandedSubBlockStart.gifContractedSubBlock.gif dot.gif{
46InBlock.gif  case CTRL_CLOSE_EVENT:       //用户要关闭Console了
47InBlock.gif   Debug.WriteLine("Close");
48InBlock.gif   break;
49ExpandedSubBlockEnd.gif }

50InBlock.gif
51InBlock.gif return false;
52ExpandedSubBlockEnd.gif    }

53ExpandedSubBlockEnd.gif}

54ExpandedBlockEnd.gif}

55 None.gif
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值