• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
BearRui(AK-47)
花开有时,错过了一日便错过了一季,就象人生错过了相遇,就不再找寻到美丽的相聚
博客园    首页    新随笔    联系   管理    订阅  订阅
如何捕捉控制台程序的关闭事件。

最近要做个控制台程序,在用户关闭程序的时候要做些处理,但控制台程序却没有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
[作者]:BearRui(AK-47)
[博客]: http://www.cnblogs.com/BearsTaR/
[声明]:本博所有文章版权归作者所有(除特殊说明以外),转载请注明出处.
posted on 2006-04-07 10:20  BearRui(AK-47)  阅读(3445)  评论(4)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3