.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.

转载于:https://www.cnblogs.com/allanli/p/3288987.html

你可能感兴趣的:(.NET控制台程序监听程序退出)