CreateWindow () in Visual C ++ always returns null

Here is my code, at the WinMain entry point I registered the class and tried to create the window, but the CreateWindow () function always returns NULL. However, the RegisterClass () function was successful. What I did wrong?

#include <Windows.h>
#include <stdio.h>


LRESULT CALLBACK event(HWND, UINT, WPARAM, LPARAM)
{


    return 0;
}

int CALLBACK WinMain(
    _In_ HINSTANCE hInstance,
    _In_ HINSTANCE hPrevInstance,
    _In_ LPSTR     lpCmdLine,
    _In_ int       nCmdShow
    )
{
    WNDCLASS wndClass;
    wndClass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
    wndClass.hCursor = LoadCursor(NULL, IDC_ARROW);
    wndClass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
    wndClass.hInstance = hInstance;
    wndClass.lpszMenuName = NULL;
    wndClass.lpfnWndProc = event;
    wndClass.lpszClassName = L"ME";
    wndClass.cbClsExtra = 0;
    wndClass.cbWndExtra = 0;
    wndClass.style = CS_HREDRAW | CS_VREDRAW;

    int err = RegisterClass(&wndClass);
    if (err < 0)
    {
        MessageBox(NULL, L"Can not register window class!", L"Error", 0);
        return -1;
    }
    HWND hwnd;
    hwnd = CreateWindow(L"ME",
    L"Test",
    WS_OVERLAPPEDWINDOW, 
    100,
    100, 
    300, 
    300, 
    NULL,
    NULL,
    hInstance, 
    NULL);
    if (hwnd == NULL)
    {
        MessageBox(NULL, L"Can not create window!", L"Error", 0);
        return -1;
    }
    ShowWindow(hwnd, SW_NORMAL);
    UpdateWindow(hwnd);

    MSG msg;
    while (GetMessage(&msg, NULL, 0, 0))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    return 0;
}

      

+3


source to share


1 answer


LRESULT CALLBACK event(HWND, UINT, WPARAM, LPARAM)
{
    return 0;
}

      

This is a fundamentally broken window procedure. Calling DefWindowProc () for messages that you do not process yourself is optional.



For now, it won't create a window because you are returning FALSE for the WM_NCCREATE message. It is supposed to return TRUE for the window to be created. You also won't get an error code from GetLastError (), since as far as the OS is concerned, you deliberately refused to allow window creation. Fix:

LRESULT CALLBACK event(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
{
    return DefWindowProc(hwnd, msg, wparam, lparam);
}

      

+9


source







All Articles