如何拦截 Console (控制台)窗口的关闭消息?

2025-03-20 14:26:53
推荐回答(1个)
回答1:

windows的console有专门的函数:SetConsoleCtrlHandler(...),参考代码如下:

#include 
#include  

using namespace std;

BOOL CtrlHandler( DWORD fdwCtrlType );

int main(int argc, char** argv) 
{
 if( SetConsoleCtrlHandler( (PHANDLER_ROUTINE) CtrlHandler, TRUE ) ) 
  { 
    cout << "Control Handler is installed" << endl; 
    cout << " Ctrl+C, Ctrl+Break, logging off or closing console NOW intercepted." << endl;
    cout << " ... into message loop.\n" << endl;  
    while( 1 ){ } 
  } 
  else 
    cout << "Control handler setting failed...." << endl;
    return 0;    
}

BOOL CtrlHandler( DWORD fdwCtrlType ) 

  switch( fdwCtrlType ) 
  {     
    case CTRL_C_EVENT: 
      printf( "Ctrl-C event\n\n" );
      return( TRUE );
     
    case CTRL_CLOSE_EVENT: 
      printf( "Ctrl-Close event\n\n" );
      return( TRUE ); 
 
    case CTRL_BREAK_EVENT:       
      printf( "Ctrl-Break event\n\n" );
      return FALSE; // pass thru, let the system to handle the event.
 
    case CTRL_LOGOFF_EVENT:       
      printf( "Ctrl-Logoff event\n\n" );
      return FALSE; // pass thru, let the system to handle the event.
 
    case CTRL_SHUTDOWN_EVENT:       
      printf( "Ctrl-Shutdown event\n\n" );
      return FALSE; // pass thru, let the system to handle the event.
 
    default: 
      return FALSE; 
  } 
}

运行结果:

Control Handler is installed
 Ctrl+C, Ctrl+Break, logging off or closing console NOW intercepted.
 ... into message loop.
 
Ctrl-C event

Ctrl-Break event

^C