资讯   |   开发   |   选机中心   |   产品大全 | IBM | 惠普 | 联想 | 戴尔 | 苹果 | 神舟
更多: | 华硕 | 明基 | 方正 | 紫光 | TCL | 夏新 | 联宝 | 宏碁 | 七喜 | 长城 | 清华同方 | 海尔 | 三星 | 东芝 | 索尼 | 富士通 | LG | 技术 | ddnoon
当前位置:笔记本 > 软件开发 >
Advertisement
文章正文

在console程序中,如何捕捉console程序的关闭信息呢?

类型:转载   责任编辑:asp.net   日期:2007/05/23


热门软件下载:


   

在窗体中,我能捕捉窗体的关闭信息,可以根据事件驱动捕捉。  
  请问console程序的关闭事件是否也能捕捉到呢?  
  或者说console程序关闭(就是那个小X的按钮)是什么样的机制呢?  
 

网友回答:

发表者:BearRui

能做到,只能用API来实现,不过麻烦点而已:  
   
  下面代码刚刚做的,测试通过:  
  ======================================================  
  using   System;  
  using   System.Windows.Forms;  
  using   System.Diagnostics;  
  using   System.Runtime.InteropServices;  
   
  namespace   WindowsApplication2  
  {  
   
  public   delegate   bool   ConsoleCtrlDelegate(int   dwCtrlType);  
   
  public   class   ClsMain  
  {  
  //The   SetConsoleCtrlHandler   function   adds   or   removes   an   application-defined   HandlerRoutine   function    
  //from   the   list   of   handler   functions   for   the   calling   process.  
  [DllImport("kernel32.dll")]  
  private   static   extern   bool   SetConsoleCtrlHandler(ConsoleCtrlDelegate   HandlerRoutine,bool   Add);  
  //一個Ctrl   +   C的信號被接收,該信號或來自鍵盤,或來自GenerateConsoleCtrlEvent   函數  
  private   const   int   CTRL_C_EVENT   =   0;  
  //一個   Ctrl   +   Break   信號被接收,該信號或來自鍵盤,或來自GenerateConsoleCtrlEvent   函數  
  private   const   int   CTRL_BREAK_EVENT   =   1;  
  //當用戶系統關閉Console時,系統會發送此信號到此  
  private   const   int   CTRL_CLOSE_EVENT   =   2;  
  //當用戶退出系統時系統會發送這個信號給所有的Console程序。該信號不能顯示是哪個用戶退出。  
  private   const   int   CTRL_LOGOFF_EVENT   =   5;  
  //當系統將要關閉時會發送此信號到所有Console程序  
  private   const   int   CTRL_SHUTDOWN_EVENT   =   6;  
   
  [STAThread]  
  static   void   Main()    
  {  
  ClsMain   cls=new   ClsMain();              
  }  
   
  public   ClsMain()  
  {  
  //   用API安装事件处理  
  ConsoleCtrlDelegate   newDelegate=new   ConsoleCtrlDelegate(HandlerRoutine);  
                                bool   bRet=SetConsoleCtrlHandler(newDelegate,true);  
  if(bRet==false)     //安装事件处理失败  
  {  
  Debug.WriteLine("失败");  
  }  
  else  
  {  
  Console.WriteLine("ok");  
  Console.Read();  
  }  
                    }  
        ///   <summary>  
        ///   处理消息的事件  
        ///   </summary>  
        private   static   bool   HandlerRoutine(int   CtrlType)  
        {  
  switch(CtrlType)  
  {  
  case   CTRL_CLOSE_EVENT:               //用户要关闭Console了  
  Debug.WriteLine("Close");  
  break;  
  }  
   
  return   false;  
          }  
  }  
  }


 

 
热门推荐笔记本: IBM笔记本
相关文章:
笔记本相关:
IT技术文章:
webmaster:popbb@126.com   最佳浏览:1024X768 MSIE
©2007 popbb.net All Rights Reserved