Chinaunix首页 | 论坛 | 博客
  • 博客访问: 84014
  • 博文数量: 11
  • 博客积分: 479
  • 博客等级: 下士
  • 技术积分: 145
  • 用 户 组: 普通用户
  • 注册时间: 2009-05-12 15:34
文章分类
文章存档

2011年(5)

2010年(3)

2009年(3)

分类: C/C++

2011-03-31 09:18:29

如果你想按照posix方式(处理signal),请看MSDN:
%28vs.71%29.aspx

Registering a Control Handler Function
转自MSDN



This is an example of the function that is used to install a control handler.

When a CTRL+C signal is received, the control handler returns TRUE, indicating that it has handled the signal. Doing this prevents other control handlers from being called.

When a CTRL_CLOSE_EVENT signal is received, the control handler returns TRUE, causing the system to display a dialog box that gives the user the choice of terminating the process and closing the console or allowing the process to continue execution. If the user chooses not to terminate the process, the system closes the console when the process finally terminates.

When a CTRL+BREAK, CTRL_LOGOFF_EVENT, or CTRL_SHUTDOWN_EVENT signal is received, the control handler returns FALSE. Doing this causes the signal to be passed to the next control handler function. If no other control handlers have been registered or none of the registered handlers returns TRUE, the default handler will be used, resulting in the process being terminated.



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

阅读(6318) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~