How do you place sub controls inside a group box?

c, user-interface, winapi

Solution

The problem is having the groupbox as the controls' parent. Groupboxes are not supposed to have any children and using them as parents will cause all kinds of errors (including painting, keyboard navigation and message propagation). Just change the parent in the buttons' CreateWindow call from group_box to hwnd (i.e. the dialog).

I'm guessing you used the groupbox as the parent in order to position the other controls easily inside it. The proper way to do this is to get the position of the groupbox client area and map it to the client area of the dialog. Everything placed in the resulting RECT will then appear inside the groupbox. Since groupboxes don't actually have a client area, it can be calculated with something like this:

// Calculate the client area of a dialog that corresponds to the perceived
// client area of a groupbox control. An extra padding in dialog units can
// be specified (preferably in multiples of 4).
//
RECT getClientAreaInGroupBox(HWND dlg, int id, int padding = 0) {
    HWND group = GetDlgItem(dlg, id);
    RECT rc;
    GetWindowRect(group, &rc);
    MapWindowPoints(0, dlg, (POINT*)&rc, 2);

    // Note that the top DUs should be 9 to completely avoid overlapping the
    // groupbox label, but 8 is used instead for better alignment on a 4x4
    // design grid.
    RECT border = { 4, 8, 4, 4 };
    OffsetRect(&border, padding, padding);
    MapDialogRect(dlg, &border);

    rc.left += border.left;
    rc.right -= border.right;
    rc.top += border.top;
    rc.bottom -= border.bottom;
    return rc;
}

Note that the same applies to Tab controls. They too are not designed to be parents and will exhibit similar behavior.

Problem

When I enable common control visual style support (InitCommonControls()) and I am using any theme other then Windows Classic Theme, buttons inside a group box appear with a black border with square corners. Windows Classic Theme appears normal, as well as when I turn off visual styling. I am using the following code: ``` group_box = CreateWindow(TEXT("BUTTON"), TEXT("BS_GROUPBOX"), WS_CHILD | WS_VISIBLE | BS_GROUPBOX | WS_GROUP, 10, 10, 200, 300, hwnd, NULL, hInstance, 0); push_button = CreateWindow(TEXT("BUTTON"), TEXT("BS_PUSHBUTTON"), WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON, 40, 40, 100, 22, group_box, NULL, hInstance, 0); ``` EDIT: The issue occurs with radio buttons as well EDIT: I am not using any dialogs/resources, only CreateWindow/Ex. I am compiling under Visual C++ 2008 Express SP1, with a generic manifest file Screenshot http://img.ispankcode.com/black_border_issue.png

Original source