【问题标题】:How to handle shutdown \ logoff in console application?如何在控制台应用程序中处理关机\注销?
【发布时间】:2012-05-21 07:12:43
【问题描述】:

我正在用 C++ 编写一个控制台应用程序。

我使用 SetConsoleCtrlHandler 来捕获任何关闭的应用程序(CTRL+C、关闭控制台、Windows 关闭或注销)。

#include <windows.h> 
#include <stdio.h> 

BOOL CtrlHandler( DWORD fdwCtrlType ) 
{   
  switch( fdwCtrlType ) 
  { 
    // Handle the CTRL-C signal. 
    case CTRL_C_EVENT: 
      printf( "Ctrl-C event\n\n" );
      Beep( 750, 300 );
      return( TRUE );

    // CTRL-CLOSE: confirm that the user wants to exit. 
    case CTRL_CLOSE_EVENT: 
      Beep( 600, 200 ); 
      printf( "Ctrl-Close event\n\n" );
      return( TRUE ); 

    // Pass other signals to the next handler. 
    case CTRL_BREAK_EVENT: 
      Beep( 900, 200 ); 
      printf( "Ctrl-Break event\n\n" );
      return FALSE; 

    case CTRL_LOGOFF_EVENT: 
      Beep( 1000, 200 ); 
      printf( "Ctrl-Logoff event\n\n" );
      return FALSE; 

    case CTRL_SHUTDOWN_EVENT: 
      Beep( 750, 500 ); 
      printf( "Ctrl-Shutdown event\n\n" );
      return FALSE; 

    default: 
      return FALSE; 
  } 
} 

int main( void ) 
{       
  //MessageBoxA(0, "test", "test", 0); // ****************

  if( SetConsoleCtrlHandler( (PHANDLER_ROUTINE) CtrlHandler, TRUE ) ) 
  { 
    printf( "\nThe Control Handler is installed.\n" ); 
    printf( "\n -- Now try pressing Ctrl+C or Ctrl+Break, or" ); 
    printf( "\n    try logging off or closing the console...\n" ); 
    printf( "\n(...waiting in a loop for events...)\n\n" ); 

    while( 1 ){ } 
  } 
  else 
  {
    printf( "\nERROR: Could not set control handler"); 
    return 1;
  }
  return 0;
}

这是 msdn 示例,它工作正常,直到我取消注释标记的行。当我这样做时,我的应用程序会处理 CTRL+C、CTRL+Break 和控制台关闭,但在关机或注销时它只是关闭而没有任何反应。

Windows 7、MSVC 10 快捷版

【问题讨论】:

    标签: winapi


    【解决方案1】:

    一旦您显示来自控制台应用程序的对话框,就会为该线程创建一个消息循环。

    一旦你有了消息循环,你就必须处理WM_ENDSESSIONrelated 消息。

    【讨论】:

    • 这不仅发生在 MessageBoxA 之后,还发生在 OemToCharBuffA 或 boost::asio 中的某些调用
    • 我在另外的线程中创建了不可见的窗口并在它的 messageproc 中处理 WM_ENDSESSION
    猜你喜欢
    • 2011-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多