zoukankan      html  css  js  c++  java
  • .NET控制台程序监听程序退出

    There are mainly 2 types of Win32 applications, console application and window application. They have different way in handling application exit. To force Window application to exit, you need to send out WM_CLOSE message to the main window handle. That's pretty simple to handle. You can hook up to Application.ApplicationExit or Form.Close at the form level. However, in a console application, it is a little bit different. Console applications are somehow modeled after DOS console application where usually an application exits when stdin is dead or Ctrl+C is pressed. To handle this properly in C#, you can set a delegate to SetConsoleCtrlHandler.You will have an opportunity to clean up resource or finish your work before the application actually exits. 

    // Declare the SetConsoleCtrlHandler function
    // as external and receiving a delegate.
    
    [DllImport("Kernel32")]
    public static extern bool SetConsoleCtrlHandler(HandlerRoutine Handler, bool Add);
    
    // A delegate type to be used as the handler routine
    // for SetConsoleCtrlHandler.
    public delegate bool HandlerRoutine(CtrlTypes CtrlType);
    
    // An enumerated type for the control messages
    // sent to the handler routine.
    public enum CtrlTypes
    {
        CTRL_C_EVENT = 0,
        CTRL_BREAK_EVENT,
        CTRL_CLOSE_EVENT,
        CTRL_LOGOFF_EVENT = 5,
        CTRL_SHUTDOWN_EVENT
    }
    
    private static bool ConsoleCtrlCheck(CtrlTypes ctrlType)
    {
        // Put your own handler here
        return true;
    }
    
    ...
    
    SetConsoleCtrlHandler(new HandlerRoutine(ConsoleCtrlCheck), true);
    

    转自Geekswithblogs.

  • 相关阅读:
    经典SQL语句大全
    SQL中With AS
    SQL Server 2008 r2 安装过程图解
    TFS2010中如何添加用户
    SQL中标准函数范例
    关闭子窗体时刷新父窗体
    sharepoint网站备份和还原
    LogHelper类
    TFS2010用户解锁
    ADHelper类
  • 原文地址:https://www.cnblogs.com/allanli/p/3288987.html
Copyright © 2011-2022 走看看