title: Shut down a ATL application cleanly
body: <p>I have developed a console ATL application and want to trap the close?, exit?, terminate? event so that I can close log files and perform a general clean-up on exit.</p>
  
  <p>How can I trap the 'terminate' event that would result from someone ending the .exe in the task manager?</p>
  
  <p><strong>EDIT:</strong></p>
  
  <p>It's a console application, I've attached the main class. Could you possibly point to where and how I should use <code>SetConsoleCtrlHandler</code>?</p>
  
  <pre><code>// Override CAtlExeModuleT members
  int WinMain(int nShowCmd) throw()
  {   
      if (CAtlBaseModule::m_bInitFailed) //ctor failed somewhere
      {
          ATLASSERT(0);
          return -1;
      }
  
      HRESULT hr = S_OK;
  
      LPTSTR lpCmdLine = GetCommandLine(); //this line necessary for _ATL_MIN_CRT
  
      if( ParseCommandLine( lpCmdLine, &amp;hr ) )
      {
          if( SUCCEEDED( RegisterClassObjects( CLSCTX_LOCAL_SERVER, REGCLS_MULTIPLEUSE ) ) )
          {
              CComPtr&lt;IRORCAdapterMain&gt; pAdapter;
  
              if( SUCCEEDED( pAdapter.CoCreateInstance( L"RORCAdapter.RORCAdapterMain" ) ) )
              {
                  if( SUCCEEDED( pAdapter-&gt;StartAdapter() ) )
                  {
                      MSG msg;
  
                      while( GetMessage( &amp;msg, 0, 0, 0 ) )
                          DispatchMessage( &amp;msg );
                  }
              }
  
              RevokeClassObjects();
          }
      }
  </code></pre>