Creating a Control

Windows provides two ways to create a control:

Within a dialog box

Within the client area of any other type of window

This chapter discusses using controls in a standard window. For a description of how to create controls within a dialog box, see Chapter 21, “Dialog Boxes.”

To create a control in a window other than a dialog box, use the CreateWindow function, just as you would to create any window. When creating a control, specify the following information:

The control's window class

The control style

The control's parent window

The control ID

The CreateWindow function returns a handle to the control that you can use in subsequent functions to move, size, paint, or destroy a window, or to direct a window to carry out tasks.

The following example shows how to create a push-button control:

hButtonWnd = CreateWindow(

“Button”, /* window control class */

“OK”, /* button label */

BS_PUSHBUTTON | WS_CHILD | WS_VISIBLE, /* control styles */

20, /* x-coordinate */

40, /* y-coordinate */

30, /* width in pixels */

12, /* height in pixels */

hWnd, /* parent window */

IDOK, /* control ID */

hInstance, /* instance handle */

NULL);

This example creates a push-button control that belongs to the Button window class and has the BS_PUSHBUTTON style. The control is a child window and will be visible when first created. The WS_CHILD style is required, but you do not need to specify the WS_VISIBLE style if you plan to use the ShowWindow function to show the control. CreateWindow places the control at the point (20, 40) in the parent window's client area. The width and height are 30 and 12 pixels, respectively. The parent window is identified by the hWnd handle. The constant IDOK is the control identifier.

The rest of this section explains how to specify the control's window class, control style, parent window, and control ID.