windows 控制台程序 响应 Ctrl+C

来源:互联网 发布:机械加工工艺编程员 编辑:程序博客网 时间:2024/06/06 03:12
[cpp] view plain copy
  1. #include <windows.h>   
  2. #include <stdio.h>   
  3.    
  4. BOOL CtrlHandler( DWORD fdwCtrlType )   
  5. {   
  6.   switch( fdwCtrlType )   
  7.   {   
  8.     // Handle the CTRL-C signal.   
  9.     case CTRL_C_EVENT:   
  10.       printf( "Ctrl-C event\n\n" );  
  11.       Beep( 750, 300 );   
  12.       return( TRUE );  
  13.    
  14.     // CTRL-CLOSE: confirm that the user wants to exit.   
  15.     case CTRL_CLOSE_EVENT:   
  16.       Beep( 600, 200 );   
  17.       printf( "Ctrl-Close event\n\n" );  
  18.       return( TRUE );   
  19.    
  20.     // Pass other signals to the next handler.   
  21.     case CTRL_BREAK_EVENT:   
  22.       Beep( 900, 200 );   
  23.       printf( "Ctrl-Break event\n\n" );  
  24.       return FALSE;   
  25.    
  26.     case CTRL_LOGOFF_EVENT:   
  27.       Beep( 1000, 200 );   
  28.       printf( "Ctrl-Logoff event\n\n" );  
  29.       return FALSE;   
  30.    
  31.     case CTRL_SHUTDOWN_EVENT:   
  32.       Beep( 750, 500 );   
  33.       printf( "Ctrl-Shutdown event\n\n" );  
  34.       return FALSE;   
  35.    
  36.     default:   
  37.       return FALSE;   
  38.   }   
  39. }   
  40.    
  41. int main( void )   
  42. {   
  43.   if( SetConsoleCtrlHandler( (PHANDLER_ROUTINE) CtrlHandler, TRUE ) )   
  44.   {   
  45.     printf( "\nThe Control Handler is installed.\n" );   
  46.     printf( "\n -- Now try pressing Ctrl+C or Ctrl+Break, or" );   
  47.     printf( "\n    try logging off or closing the console...\n" );   
  48.     printf( "\n(...waiting in a loop for events...)\n\n" );   
  49.    
  50.     while( 1 ){ }   
  51.   }   
  52.   else   
  53.   {  
  54.     printf( "\nERROR: Could not set control handler");   
  55.     return 1;  
  56.   }  
  57. return 0;  
  58. }  
原创粉丝点击