Search code examples
c++winapichildwindow

Why it cant create the child window?


Can anyone tell me why the child window cannot be created? I'm using the forgers win32api guide but I cannot figure out what is the problem.

When the program starts running I have all of the controls, but when I click on the 'new' menuitem I get the error message. This is right after the winmain.

Other things like menuitems, the tool and status bars, opening or saving files works.

**HWND CreateNewMDIChild(HWND hMDIClient)
{
    MDICREATESTRUCT mcs;
    HWND hChild;
    mcs.szTitle = "[Untitled]";
    mcs.szClass = g_szChildClassName;
    mcs.hOwner  = GetModuleHandle(NULL);
    mcs.x = mcs.cx = CW_USEDEFAULT;
    mcs.y = mcs.cy = CW_USEDEFAULT;
    mcs.style = MDIS_ALLCHILDSTYLES;
    hChild = (HWND)SendMessage(hMDIClient, WM_MDICREATE, 0, (LONG)&mcs);

    if(!hChild)
    {
        MessageBox(hMDIClient, "MDI Child creation failed.", "Oh Oh...",
            MB_ICONEXCLAMATION | MB_OK);
    }
    return hChild;

}**

Solution

  • That's an unfortunate bug in the sample code, that prevents it from running on 64-bit Windows. The final parameter to SendMessage is of type LPARAM (an alias for LONG_PTR). Casting it to LONG truncates it to 4 bytes, not quite sufficient for a 64-bit pointer (see Data Type Ranges).

    Change the following line

    hChild = (HWND)SendMessage(hMDIClient, WM_MDICREATE, 0, (LONG)&mcs);
    

    to

    hChild = (HWND)SendMessage(hMDIClient, WM_MDICREATE, 0, (LPARAM)&mcs);
    

    and the code should run as expected.