Window creation fails with non-NULL hMenu parameter

490 views Asked by At

In addition to the main window, I'm trying to create another top level window. The problem is that when I'm setting the second window's hMenu parameter to a non-NULL value, it doesn't show up.

e.g:

This window shows up (hMenu == 0)

case IDC_BUTTON_SEND_COMMAND:
{
    CreateWindowExW(NULL,
                    L"CommandWindow", L"Send Command",
                    WS_VISIBLE | WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX,
                    100, 100, 600, 400,
                    NULL,
                    (HMENU)0,
                    (HINSTANCE)GetWindowLong(hwnd, GWL_HINSTANCE), NULL);
    break;
}

This window doesn't show up (hMenu == 4)

case IDC_BUTTON_SEND_COMMAND:
{
    CreateWindowExW(NULL,
                    L"CommandWindow", L"Send Command",
                    WS_VISIBLE | WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX,
                    100, 100, 600, 400,
                    NULL,
                    (HMENU)4,
                    (HINSTANCE)GetWindowLong(hwnd, GWL_HINSTANCE), NULL);
    break;
}

I'm using Windows 7.

2

There are 2 answers

8
IInspectable On BEST ANSWER

Passing (HMENU)4 as the hMenu parameter to CreateWindowEx to create a top level window tells the system to attach a menu to it. This menu has the menu handle 4. A menu handle (HMENU) is returned from functions like CreateMenu. If the handle is not a valid HMENU window creation fails.

Your observation, that the window doesn't show up is misleading yourself into believing that the window actually exists. The window doesn't exist, and CreateWindowEx returns NULL. Checking return values is advisable, and calling GetLastError when an API call fails is usually quite helpful.

0
Love N On

Your window fails creation because (HMENU)4 is not a valid menu handle, such as those returned from CreateMenu() or LoadMenu().

(HMENU)4 would be a valid control ID, if the window was a child window. MAKEINTRESOURCE(4) would also be a valid menu resource ID, if specified in the WNDCLASS[EX] struct when you register your class with RegisterClass[Ex].

You need to specify a valid menu handle if you want to use the hMenu parameter of CreateWindow[Ex] when you create a top level window.

A menu handle can be acquired either using an API like CreateMenu(), or by loading a menu resource, f.ex with LoadMenu( GetModuleHandle(NULL), MAKEINTRESOURCE(4) ).

Hope that helps.