Check Boxes

A check box is a square box with text; the text usually appears to the right of the check box. (If you include the BS_LEFTTEXT style when creating the button, the text appears to the left.) Check boxes are usually incorporated in an application to allow a user to select options. The check box commonly functions as a toggle switch: Clicking the box once causes an X to appear; clicking again toggles the X off.

The two most common styles for a check box are BS_CHECKBOX and BS_AUTOCHECKBOX. When you use the BS_CHECKBOX style, you must set the X mark yourself by sending the control a BM_SETCHECK message. The wParam parameter is set to 1 to create an X and to 0 to remove it. You can obtain the current check state of the box by sending the control a BM_GETCHECK message. You might use code like this to toggle the X mark when processing a WM_COMMAND message from the control:

SendMessage (LOWORD (lParam), BM_SETCHECK, (WORD)

!SendMessage (LOWORD (lParam), BM_GETCHECK, 0, 0L), 0L) ;

Note the ! operator in front of the second SendMessage call. The low word of lParam is the child window handle passed to your window procedure in the WM_COMMAND message. When you later need to know the state of the button, send it another BM_GETCHECK message. Or you can retain the current check state in a static variable in your window procedure. You can also initialize a BS_CHECKBOX check box with an X by sending it a BM_SETCHECK message:

SendMessage (hwndButton, BM_SETCHECK, 1, 0L) ;

For the BS_AUTOCHECKBOX style, the button control itself toggles the X on and off. Your window procedure can ignore WM_COMMAND messages. When you need the current state of the button, send the control a BM_GETCHECK message:

nCheck = (WORD) SendMessage (hwndButton, BM_GETCHECK, 0, 0L) ;

The value of nCheck is TRUE or nonzero if the button is checked, FALSE or zero if not.

The other two check box styles are BS_3STATE and BS_AUTO3STATE. As their names indicate, these styles can display a third state as well—a gray color within the check box—which occurs when you send the control a WM_SETCHECK message with wParam equal to 2. The gray color indicates to the user that the box cannot be checked_ that is, that it's disabled. However, the check box control continues to send messages to the parent when the box is clicked. Better methods for disabling a check box are described later.

The check box is aligned with the rectangle's left edge and is centered within the top and bottom dimensions of the rectangle that were specified during the CreateWindow call. Clicking anywhere within the rectangle causes a WM_COMMAND message to be sent to the parent. The minimum height for a check box is one character height. The minimum width is the number of characters in the text plus two.