zoukankan      html  css  js  c++  java
  • c# 如何捕捉控制台程序的关闭事件。(转)

    最近要做个控制台程序,在用户关闭程序的时候要做些处理,但控制台程序却没有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/
    [声明]:本博所有文章版权归作者所有(除特殊说明以外),转载请注明出处.
  • 相关阅读:
    没有上司的舞会
    邮票面值设计
    小木棍
    简单的试炼
    区间质数
    加工生产调度
    泥泞的道路
    总数统计
    中庸之道

  • 原文地址:https://www.cnblogs.com/xihong2014/p/15118222.html
Copyright © 2011-2022 走看看