Visual C++ 中的 CreateWindow() 总是 return null

CreateWindow() in Visual C++ always return null

这是我的代码,在 WinMain 入口点我注册了一个 class 并试图创建一个 window,但是 CreateWindow() 函数总是 return NULL。但是 RegisterClass() 函数确实成功了。我做错了什么?

#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;
}
LRESULT CALLBACK event(HWND, UINT, WPARAM, LPARAM)
{
    return 0;
}

这是一个从根本上被破坏的 window 过程。为您自己不处理的消息调用 DefWindowProc() 不是可选的。

现在它不会创建 window 因为你 return FALSE WM_NCCREATE 消息。它应该 return TRUE 以允许创建 window。您也不会从 GetLastError() 获得错误代码,就 OS 而言,您故意拒绝允许创建 window。修复:

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