CreateWindowW always returns null

Viewed 53

I'm new to C++ coding, and I'm trying to create a window using the Win32 API, but CreateWindowW() always return a NULL value. I tried to use CreateWindowEx() and CreateWindow(), but the same results.

Here is the code I used:

#include<windows.h>

LRESULT CALLBACK WindowProcedure(HWND, UINT, WPARAM, LPARAM);

INT WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,PSTR lpCmdLine, INT nCmdShow)
{
    WNDCLASSW wc = { 0 };
    wc.hbrBackground = (HBRUSH)COLOR_WINDOW;
    wc.hCursor = LoadCursor(NULL, IDC_CROSS);
    wc.hInstance = hInstance;
    wc.lpszClassName = L"myWindowClass";
    wc.lpfnWndProc = WindowProcedure;

    if (!RegisterClassW(&wc))
    {
        MessageBox(NULL, L"Regesteration of Window Class had Failed", L"Error", MB_ICONERROR);
        return -1;
    }

    HWND x =  CreateWindowW(L"myWindowClass",L"NEW Window",WS_OVERLAPPEDWINDOW|WS_VISIBLE,CW_USEDEFAULT,CW_USEDEFAULT,800,600,NULL,NULL,NULL,NULL);
    if (!x)
    {
        MessageBox(NULL, L"Creation of Window Class had Failed", L"Error", MB_ICONERROR);
    }
    MSG msg = { 0 };

    while (GetMessage(&msg, NULL, NULL, NULL))
    {
        TranslateMessage(&msg);
        DispatchMessageW(&msg);
    }

    return 0;
}

LRESULT CALLBACK WindowProcedure(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
{
    switch (msg)
    {
        case WM_DESTROY:
            PostQuitMessage(0);
            break;
         
        default:
            DefWindowProcW(hwnd, msg, wparam, lparam);
    }

    return 0;
}

Can any one please tell me what I'm doing wrong?

1 Answers

The window procedure always returns 0, which ultimately cancels window creation. As outlined in the documentation for CreateWindowExW:

The CreateWindowEx function sends WM_NCCREATE, WM_NCCALCSIZE, and WM_CREATE messages to the window being created.

The first message, WM_NCCREATE, has the following in the documentation:

If the application returns FALSE, the CreateWindow or CreateWindowEx function will return a NULL handle.

FALSE has a value of 0, so when your window procedure returns 0, window creation is terminated. A call to GetLastError will usually also return 0 (i.e. no error) in this case.

You'll want to have your window procedure return the value returned by the call to DefWindowProcW instead, i.e.

default:
    return DefWindowProcW(hwnd, msg, wparam, lparam);
Related