0

For some reason I get "Invalid window handle" error direct after GetMessage() loop ends but I'm not even passing a HWND to it so how come I get this error? :s

MSG Message;
while(GetMessage(&Message, NULL, 0, 0) != 0)
{
    TranslateMessage(&Message);
    DispatchMessage(&Message);
}
ShowError();

It's not anything wrong with ShowError as I use it in more than this app and doesn't get this error...

void ShowError()
{
    DWORD ErrorCode = GetLastError();
    if(ErrorCode == ERROR_SUCCESS) return;

    LPTSTR lpszBuffer = NULL;
    FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, ErrorCode, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&lpszBuffer, 0, NULL);

    MessageBox(NULL, lpszBuffer, NULL, MB_OK | MB_ICONERROR);
    LocalFree(lpszBuffer);
}
Traxmate
  • 105
  • 1
  • 6

2 Answers2

3

You should only ever call GetLastError() when a Windows function returned a failure code. This is certainly not the case in your snippet, you only test the GetMessage() return value for != 0. Which could be 0, indicating that your program stopped normally with WM_QUIT. Or it could be -1, a real error.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
0

Since I just had the same error here is my cause and solution.


Cause: Your WndProc is probably causing this error. When you close your window the DefWindowProc function sets last error to 1400 = Invalid window handle if you use PostQuitMessage not "correctly". The message being processed when this error arises is probably WM_NCLBUTTONDOWN. If the window has been destroyed no clicks on it can be processed. In fact there are a few messages that can't be processed by your window.
Solution: After PostQuitMessage no more DefWindowProc! Just return your result code and exit WndProc.
// translated from C#
LRESULT WndProc(HWND window, int msg, WPARAM wParam, LPARAM lParam)
{
    if (msg == WM_CLOSE)
    {
        PostQuitMessage(0);
        return 0; // comment this line to get the error again
    }
    return DefWindowProc(window, msg, wParam, lParam);
}
Bitterblue
  • 13,162
  • 17
  • 86
  • 124