8.5.3 Adding a CreateWindow Function

Before you can create the edit control, you must retrieve the dimensions of the client area to determine the size of the control. After creating the main window, add the following statements to the WinMain function:

GetClientRect(hWnd, (RECT FAR*) &Rect);

hEditWnd = CreateWindow("EDIT",
    NULL,
    WS_CHILD | WS_VISIBLE |
    ES_MULTILINE |
    WS_VSCROLL | WS_HSCROLL |
    ES_AUTOHSCROLL | ES_AUTOVSCROLL,
    0,
    0,
    Rect.right - Rect.left,
    Rect.bottom - Rect.top,
    hWnd,
    IDC_EDIT,
    hinst,
    NULL);

if (!hEditWnd) {
    DestroyWindow(hWnd);
    return NULL;
}

The GetClientRect function retrieves the dimensions of the main window's client area and places that information in the Rect structure. The CreateWindow function creates the edit control, using the width and height computed by the Rect structure.

The CreateWindow function creates the edit control, using the predefined EDIT control class and specifying the WS_CHILD window style. You can use the predefined controls as child windows only, not as main or pop-up windows. Since a child window requires a parent window, you must specify the handle of the main window, hWnd, when calling the function.

For this edit control, a number of control styles are also specified. These control styles, like window styles, define how the edit control will look and operate. This one is a multiline control, meaning the user will be able to type more than one line of text in it. Also, the control will automatically scroll horizontally or vertically if the user types more text than can fit in it.

The upper-left corner of the control is placed at the upper-left corner of the parent window's client area. A child window's coordinates are always relative to the parent window's client area. The next two arguments, Rect.right – Rect.left and Rect.bottom – Rect.top, define the height and width of the control, ensuring that it fills the client area when first displayed.

Since an edit control sends notification messages to its parent window, the control must have an identifier. Child windows cannot have menus, so use the menu argument in the CreateWindow function to specify the control identifier instead. For this control, the identifier is IDC_EDIT. Any notification messages sent to the parent window by the control will contain this identifier.

If the CreateWindow function cannot create the edit control, the function returns NULL. In such a case, your application cannot continue, so you should use the DestroyWindow function to destroy the main window before terminating the application.