BearRui(AK-47)
花开有时,错过了一日便错过了一季,就象人生错过了相遇,就不再找寻到美丽的相聚
随笔- 39  文章- 2  评论- 1291 
博客园  首页  新随笔  联系  管理  订阅 订阅
如何捕捉控制台程序的关闭事件。

最近要做个控制台程序,在用户关闭程序的时候要做些处理,但控制台程序却没有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
posted on 2006-04-07 10:20 BearRui(AK-47) 阅读(1181) 评论(2) 编辑 收藏
刷新评论刷新页面返回顶部
程序员问答社区,解决您的IT难题
博客园首页博问新闻闪存程序员招聘知识库
Copyright ©2012 BearRui(AK-47)