Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CreateWindow() in Visual C++ always return null

Here is my code, in the WinMain entry point i registered a class and tried to create a window, but the CreateWindow() function always return NULL. However the RegisterClass() function did succeed. What have i done 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;
}
like image 727
Kelvin Zhang Avatar asked Dec 24 '22 16:12

Kelvin Zhang


1 Answers

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

That's a fundamentally broken window procedure. Calling DefWindowProc() for messages that you don't handle yourself is not optional.

Right now it will not create the window because because you return FALSE for the WM_NCCREATE message. It is supposed to return TRUE to allow the window to be created. You won't get an error code from GetLastError() either, as far as the OS is concerned you intentionally refused to allow the window to get created. Fix:

LRESULT CALLBACK event(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
{
    return DefWindowProc(hwnd, msg, wparam, lparam);
}
like image 136
Hans Passant Avatar answered Jan 13 '23 19:01

Hans Passant