Why CreateWindowEx() return NULL

三世轮回 提交于 2019-12-11 14:21:40

问题


I learn the example on MSDN, but when I code, I have big trouble with CreateWindowEx(). It's return NULL, so it can't create a window. I don't understand why it return that. This code follow MSDN example. Here's my code:

#include <Windows.h>

LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);

int WINAPI wWinMain(HINSTANCE hIns, HINSTANCE hPreIns, PWSTR pCmdLine, int nCmdShow)
{
    UNREFERENCED_PARAMETER(hPreIns);
    UNREFERENCED_PARAMETER(pCmdLine);
    HWND hWnd;
    TCHAR ClassName[] = L"Learn";
    TCHAR Title[] = L"My Window";
    WNDCLASSEX wcx;
    wcx.cbSize = sizeof(WNDCLASSEX);
    wcx.style = CS_HREDRAW | CS_VREDRAW;
    wcx.hInstance = hIns;
    wcx.lpszClassName = ClassName;
    wcx.lpfnWndProc = WndProc;
    wcx.cbClsExtra = 0;
    wcx.cbWndExtra = 0;
    wcx.hbrBackground = CreateSolidBrush(RGB(238,201,0));
    wcx.hIcon = LoadIcon(hIns, IDI_APPLICATION);
    wcx.lpszMenuName = NULL;
    wcx.hCursor = LoadCursor(hIns, IDC_WAIT);
    wcx.hIconSm = LoadIcon(hIns, IDI_INFORMATION);
    // Register
    RegisterClassEx(&wcx);

    hWnd = CreateWindowEx(0, ClassName, Title, WS_OVERLAPPEDWINDOW,
    CW_USEDEFAULT, CW_USEDEFAULT, 1024, 768,
    NULL, NULL, hIns, NULL);
    if(hWnd == NULL)
    {
        MessageBox(hWnd, L"Fail!", L"Warning!", MB_OK);
        return 1;
    }
    ShowWindow(hWnd, nCmdShow);
    UpdateWindow(hWnd);
    MSG msg;
    while(GetMessage(&msg, NULL, 0, 0))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    return msg.wParam;
}

LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    switch(msg)
    {
    case WM_PAINT:
        {
            HDC hdc;
            PAINTSTRUCT ps;
            hdc = BeginPaint(hWnd, &ps);
            FillRect(hdc, &ps.rcPaint, (HBRUSH) (COLOR_WINDOW+1));
            EndPaint(hWnd, &ps);
        }
        break;
    case WM_DESTROY:
        {
            PostQuitMessage(0);
            break;
        }
    default: DefWindowProc(hWnd, msg, wParam, lParam);
    }
    return 0;
}

Thanks so much.


回答1:


  default: DefWindowProc(hWnd, msg, wParam, lParam);

That's wrong, very important that you return the value that DefWindowProc() returns. If you don't then your message handler returns FALSE for the WM_NCCREATE message. Which is documented to force CreateWindowEx() to return NULL, Windows abandons the attempt at getting the window created. Fix:

  default: return DefWindowProc(hWnd, msg, wParam, lParam);


来源:https://stackoverflow.com/questions/27213478/why-createwindowex-return-null

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!