How to Use checkboxes in MFC
A checkbox control has two states, "checked" and "unchecked." It can be applied wherever a choice is expected of the user, such as agreeing to the conditions set by a vendor before installing a software or selecting multiple choice answers. The checkbox is based on the CButton class of the MFC (Microsoft Foundation Class) Library. Using MFC Check Box controls in a program is fairly simple to learn.
Instructions
-
-
1
Launch Microsoft Visual Studio. Use the MFC AppWizard (exe) to create a Dialog-based project. Choose the default options.
-
2
Place a Check Box on the Dialog Control you just created from the controls toolbox. Right-click it, select "Properties" and give it the ID "IDC_CHECKBOX."
-
-
3
Create an event function for the Check Box. Open the Class Wizard by pressing Ctrl+W, then click the "Message Maps" tab. Select "IDC_CHECKBOX1" under "Object IDs." Next, under "Messages," select "BN_CLICKED." Now click the "Add Function" button. Accept the default function name and click "OK." Click "Edit Code" in the wizard window. Paste the following line under the "TODO" comment: "MessageBox("Clicked!");". Compile and run the code. Check the checkbox and see the message.
-
4
Demonstrate the binary function of the checkbox control. Open the Class Wizard by hitting Ctrl+W. Click the "Member Variables" tab and highlight "IDC_CHECKBOX1." Click the "Add Variable" button and name the variable "m_MyCheckBox." Select "Control" under the "Category" combo. Go back to the Design view and add a Button on the Dialog control. Right-click the Button, select "Properties" type for ID "IDC_BINARYBUTTON" and change the caption to "Get Val." Press Ctrl+W, click the "Message Maps" tab, choose "IDC_BINARYBUTTON" under "Object ID" and highlight the "BN_CLICKED" message. Click "Add Function," accept the default name and click "Edit Code." Paste the following code under the "TODO" comment:
CString strBinaryVal;
int val = m_MyCheckBox.GetCheck();
strBinaryVal.Format("The Check Box Value is : %d",strBinaryVal);
MessageBox(strBinaryVal);
-
5
Compile and run the code again. When the button is pressed and the checkbox is set, the number 1 will appear. A zero will appear when the checkbox control isn't checked.
-
1
Resources
Comments
-
AlexDen
Nov 03, 2008
The code example is very illustrative. It helped me to quickly use a check box when I didn't have time to read a manual. -
AlexDen
Nov 03, 2008
The code example is very illustrative. It helped me to quickly use a check box when I didn't have time to read a manual.