Using MFC in C++ Part 4: Controls, DDX and DDV - The check box control
(Page 4 of 9 )
As with the EDITTEXT control, we create both the check box control within our resource file. Updating our example resource file, we would add a check box, like this:
AUTOCHECKBOX "Able to vote?", IDCB_CANVOTE, 20, 35, 50, 15, WS_VISIBLE | WS_CHILD | WS_TABSTOPThis would add a check box to our dialog box. Its caption would be set to “Able to vote?”. MFC provides two types of check boxes: The CHECKBOX, and the AUTOCHECKBOX control. In our example above, I have used the AUTOCHECKBOX control, simply because if we chose the CHECKBOX control, we would have to handle the checking and un-checking of the box manually, which is just a pain.
The syntax of the CHECKBOX control is shown below:
[AUTO]CHECKBOX
[Caption], [Control Id], [X Pos], [Y Pos], [Width], [Height], [Style Options]The caption of the check box is the text that will be displayed next to the check box. The control id is a numerical id, which is #defined within another header file. In our example, we have used IDCB_CANVOTE. I have prefixed the check box controls id with IDCB, which is representational for “Check Box Identification”. You can, however name your controls id’s whatever you like.
It’s really simple to get and set the value of a check box control. As you can probably guess, a check box is either on or off, 1 or 0. We retrieve the value of our check box control like this:
int checkState;
CButton* pCheck = (CButton*)GetDlgItem(IDCB_CANVOTE);
checkState = pCheck->GetCheck();As with the EDITTEXT control, we retrieve a reference to the control via its id. The check box control is a member of the CButton class, so we cast it as such. The GetCheck method of the CButton class returns the current value of our check box: 0 for not checked, or 1 for checked.
To set the value of our check box control, we can use the SetCheck method, like this:
CButton* pCheck = (CButton*)GetDlgItem(IDCB_CANVOTE);
pCheck->SetCheck(1);That’s pretty much all you need to create and use a check box control because they are so simple. Let’s now look at the radio button control.
Next: The radio button control >>
More C++ Articles
More By Mitchell Harper