title: Closing Window and Thread Generates Invalid Window Handle Error - C++
body: <p>My console application spawns a new (invisible) window in its own thread.  Prior to exiting the application, it attempts to clean up, and the last call to <code>GetMessage</code> in the window's message pump fails.  <code>GetLastError</code> returns 1400, "Invalid window handle."</p>
  
  <p>This is how the clean up proceeds in the application thread:</p>
  
  <pre><code>if ( s_hNotifyWindowThread != NULL )
  {
      ASSERT(s_pobjNotifyWindow != NULL);
  
      ::PostMessage( s_pobjNotifyWindow-&gt;m_hWnd, WM_CLOSE, 0, 0 );
      ::WaitForSingleObject( s_hNotifyWindowThread, 50000L );      // Step 1: breakpoint here
      ::CloseHandle( s_hNotifyWindowThread );                      // Step 4: breakpoint here
      s_hNotifyWindowThread = NULL;
  }
  </code></pre>
  
  <p>This <code>WndProc</code> exists in the new thread created for the window:</p>
  
  <pre><code>static LRESULT CALLBACK WndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam )
  {
      switch ( uMsg )
      {
      case WM_CLOSE:
          ::DestroyWindow( hWnd );    // Step 2: breakpoint here
          break;
  
      case WM_DESTROY:
          ::PostQuitMessage( 0 );     // Step 3: breakpoint here
          break;
  
      case WM_DEVICECHANGE:
          /* Handle device change. */
          break;
  
      default:
          // Do nothing.
          break;
      }
  
      return ::DefWindowProc( hWnd, uMsg, wParam, lParam );
  }
  </code></pre>
  
  <p>This is in the window's thread function where the new window is created and my message pump is located:</p>
  
  <pre><code>s_pobjNotifyWindow = new CNotifyWindow( pParam );
  
  while ( (bRetVal = ::GetMessage(
      &amp;msg,                           // message structure
      s_pobjNotifyWindow-&gt;m_hWnd,     // handle to window whose messages are to be retrieved
      0,                              // lowest message value to retrieve
      0                               // highest message value to retrieve
      )) != 0 )
  {
      switch ( bRetVal )
      {
      case -1:                        // Error generated in GetMessage.
          TRACE(_T("NotifyWindowThreadFn : Failed to get notify window message.\r\n\tError: %d\r\n\tFile: %s\r\n\tLine: %d\r\n"), ::GetLastError(), __WFILE__, __LINE__);
          return ::GetLastError();    // Step 5: breakpoint here: Returns error 1400
          break;
  
      default:                        // Other message received.
          ::TranslateMessage( &amp;msg );
          ::DispatchMessage( &amp;msg );
          break;
      }
  }
  </code></pre>
  
  <p>What am I doing wrong?  Thanks.</p>