www.pudn.com > os_example.rar > SetConsoleCtrlHandler.cpp


#include   
#include   
#include  
#include   
 
BOOL CtrlHandler(DWORD fdwCtrlType)  
{  
    switch (fdwCtrlType)  
    {  
        // Handle the CTRL+C signal.  
  
        case CTRL_C_EVENT:  
  
            Beep(1000, 1000);  
            return TRUE;  
  
        // CTRL+CLOSE: confirm that the user wants to exit.  
  
        case CTRL_CLOSE_EVENT:  
			cout << "CTRL_CLOSE_EVENT" << endl; 
  
            return TRUE;  
  
        // Pass other signals to the next handler.  
  
        case CTRL_BREAK_EVENT:  
  
        case CTRL_LOGOFF_EVENT:  
  
        case CTRL_SHUTDOWN_EVENT:  
  
        default:  
  
            return FALSE;  
    }  
}  
  
void main(void)  
{  
    BOOL fSuccess;  
  
    fSuccess = SetConsoleCtrlHandler(  
        (PHANDLER_ROUTINE) CtrlHandler,  // handler function  
        TRUE);                           // add to list 
	cout << "Process starts." << endl; 
	Sleep(1000); 
	GenerateConsoleCtrlEvent(CTRL_C_EVENT, NULL); 
	Sleep(1000); 
    if (! fSuccess)  
        cout << "Could not set control handler" << endl; 
	cout << "Process ends." << endl; 
}