Sei sulla pagina 1di 7

Command Buttons in MFC Dialogs

The next step after learning Dialog box creation in MFC, are the controls. This article deals with the
Command Button control. We'll look at how to use the CButton class in case of the command button
controls. This article assumes the user has familiarity with the basic Windows controls. This MFC Tutorial
only concentrates on how to manipulate them using MFC.

Before using the controls, we need to have our base application with a dialog box for this MFC Tutorial.
This dialog box will be the container to hold the controls. At least from now on (for easier learning), the
Codersource MFC Tutorial articles will start using the wizard to create the base application.

To Create the Application:


1. Open the Microsoft Visual Studio 6.00. Click Menu--> File--> New and Select MFC AppWizard(exe)
option.
2. In the next MFC AppWizard screen - Step 1, Choose Dialog based application.
3. Click Finish after selecting this. All the files needed for this MFC Tutorial will be created.
4. If the project is built and run, it will open a dialog box, with two command buttons and one static
display control.
5. Close the application and come back to the Microsoft Visual studio.

The application created in the above steps of this MFC Tutorial will be used to add and use the controls.

The wizard has already created two command buttons with captions OK and Cancel. The wizard has
created two automatic handlers for each one of the buttons. When we click them, it just closes the dialog.
Delete these two command buttons and the static control. We'll create our own command buttons in our
MFC Tutorial.

Adding the command Button:


1. Open the dialog box. There must be a controls tool box appearing on the sides. Click on the
command button control and Click on the dialog box, where you want to place the button.
2. The button is placed in the dialog box and its caption is set to "Button1" by default.
3. Click the mouse on the Button and Press Enter key.
4. A Property sheet will appear, showing all the properties of the button.
5. Change the ID to IDC_MYBUTTON and change the caption to "My Button".
6. Now Press the Ctrl+W keys to invoke the class wizard.
7. Ensure that you are in the Message Maps tab.
8. Ensure that the Top right side combo (class name) contains the CMFC_Tutorial_7 class. If you have
named your application with a different name, it should have "yourapplicationdlg" selected.
9. Select the IDC_MYBUTTON on the left hand side and BN_CLICKED on the right handside of the
dialog. Then click "Add Function". Say ok to the dialog which appears eventually.
10. If you look at the list box down, it will have Onmybutton ON_IDC_MYBUTTON:BN_CLICKED inside
the list. Click on Edit Code. This will lead to the MFC_Tutorial_7Dlg.cpp.
11. The following function will be created in this file.

void MFC_Tutorial_7Dlg::OnMybutton()
{
// TODO: Add your control notification handler code here
MessageBox("My Button Clicked");
}

12. Add a line "MessageBox("My Button Clicked");" inside the function as highlighted above.
13. Now build and run the application.
14. We'll see the dialog with "My Button" command button placed on the dialog. Click on the button,
we'll see a message box.
Check Box Usage

Check boxes are used to check binary states. Yes or No answers, Male/Female kind of conditional user
interface inputs are easier with a check box. This part of Codersource MFC Tutorial explains how to use a
Check box in dialog box applications of MFC.

Check box:
There are quite a few techniques to be learnt with all the MFC Controls. Some of them related to the
Check Box control are

 Handling of Messages ( Mouse Click, Double Click etc)


 Getting and Setting check box values
 DDX mechanism
The first job for this MFC tutorial will be to create the MFC Dialog based Application. This application
will be used to hold the check boxes. This is the same set of code/steps which are used for the MFC
Tutorials explaining about the controls.

To Create the Application:


1. Open the Microsoft Visual Studio 6.00. Click Menu--> File--> New and SelectMFC
AppWizard(exe) option.
2. In the next MFC AppWizard screen - Step 1, Choose Dialog based application.
3. Click Finish after selecting this. All the files needed for this MFC Tutorial will be created.
4. If the project is built and run, it will open a dialog box, with two command buttons and one static
display control.
5. Close the application and come back to the Microsoft Visual studio.
Adding a check box:
The above application and dialog box will be used for handling check box in the tutorial. The following
steps explain how to add a check box for this MFC Tutorial:
1. Open the dialog editor of the previously created application.
2. Click on the check box from the controls toolbox and place two checkboxes on the dialog.
3. Open the properties dialog of the check box. This is done by first selecting the check box and
pressing the "Enter" key.
4. Rename the ID of one of the check boxes as IDC_FIRSTCHECKBOX and the caption as "First
check box"
5. Rename the second one's ID as IDC_SECONDCHECKBOX and the caption as Second Check
Box.
Now we'll look at the different ways of manipulating the check boxes.
Event Handling:
Check box can handle the Mouse Click and Double click events. Let us see how to trap the Mouse click
events for the check box.
 Use our previously created application for this MFC Tutorial now. Open the dialog box and Select
the "First Check box" control.
 Press the keys Ctrl + W
 On the Message Maps tab, select IDC_FIRSTCHECKBOX on the Object ID list box and
BN_CLICKED on theMessages list box.
 Click on Add Function
 After creating the function, click on the Edit code button. We'll be taken to the implementation of
the click message of the check box.
 Add a line for invoking a message box. You can use the following code indicated in bold.

void CMfc_tutorial_8Dlg::OnFirstcheckbox()
{
// TODO: Add your control notification handler code here
MessageBox ("First Check box Clicked");
}

 Build the application and Run it. If you click on the check box, you should see a message box.
Manipulating the check box:
A Check box can return a value ofTrue or False. Let's add a Command Button to get the values of
check box.
 Open the dialog editor. Add a Command Button with a caption "Get Second Box". Name the id
with IDC_GETSECONDCHECKBOXVAL.
 Press Ctrl+W and create a BN_CLICKED handler for it. On the Message Maps tab, Select
IDC_GETSECONDCHECKBOXVAL on theObject ID and select the BN_CLICKED Message.
Click on Add function with a function name as OnGetSecondBox and add the handler.
 On the Member Variables tab, select IDC_SECONDCHECKBOX and click on the "Add
Variable". Give the name of the variable asm_ctlSecondCheckBox. On the Category combo,
choose Control and theVariable Type will be automatically selected as CButton.
Now open the "mfc_tutorial_7dlg.cpp" (in your case "YourApplicationNameDlg.cpp") and look for the
OnGetSecondBox() function. Add the following code to it.

void CMfc_tutorial_8Dlg::OnGetSecondBox()
{
// TODO: Add your control notification handler code here
CString l_strCheckBoxVal;
int l_ChkBox = m_ctlSecondCheckBox.GetCheck();
l_strCheckBoxVal.Format("Second Check Box Value : %d",l_ChkBox);
MessageBox(l_strCheckBoxVal);
}

If the Second Check Box is checked, then the message box will display the string as "Second Check
Box Value : 1". If not, it will display the string as "Second Check Box Value : 0". That means, the
GetCheck function returns 1 if the control is checked and 0 if it is not.
The variable that we use is m_ctlSecondCheckBox , which was created earlier using the Member
variable tab of the class wizard.
In the same way we can use SetCheck function to set the values of the check box.
DDX mechanism:
This part of the check box MFC Tutorial deals with an elegant mechanism. This DDX mechanism is an
easier way out of the programming intricacies. MFC itself takes care of all the complexities of
programming for us. We don't have to worry about getting or setting the values of check boxes ( or any
other controls related), by calling GetCheck or SetCheck.
This is called as Dynamic Data Exchange mechanism. The MFC Framework itself keeps track of the
values on the controls. At any point of time, the values are accessible through the variables declared as
the member variables.
1. Click on the Ctrl+W to open the class wizard
2. In the Member variables tab, select the IDC_SECONDCHECKBOX and clickAdd Variable
3. Enter the variable name as m_SecondCheckBox
4. Leave the Category and Variable typesunchanged at Variable and bool. Click ok.
5. Add a new command Button with a caption "Get DDX" and add a handler to it.
6. We can now get the value of the checkbox without using theGetCheck and SetCheck functions
as follows.

void CMfc_tutorial_8Dlg::OnButton1()
{
// TODO: Add your control notification handler code here

CString l_strCheckBoxVal;
UpdateData();
int l_ChkBox = m_SecondCheckBox;
UpdateData(FALSE);
l_strCheckBoxVal.Format("Second Check Box Value : %d",l_ChkBox);
MessageBox(l_strCheckBoxVal);
}

The new code is highlighted with the bold letters. This is the way MFC handles all the controls from
which we need some values to be extracted. This Dynamic Data exchange eases the programmer's job
very much. Now we can get the same output as in the manual handling of the check box.
The CEdit class provides the functionality of an edit control in Microsoft Windows based systems. It is a
rectangular child window which can be used to enter text in GUI Programs. This article explains how to
use the CEdit class for some of the important operations to be performed in a dialog based program. This
is also applicable in SDI/MDI applications which use a dialog box.
CEdit - Setting up the program:
The following steps explain how to setup the base application/dialog box for using the edit control. The
class CEdit will be used to manipulate the edit control being used. If this basic set up is already done,
readers can skip this section and move to the next one.

 Create a new MFC AppWizard executable project as a dialog based application.


 The application can also be an SDI/MDI app, where in the dialog can be inserted as a resource
into the SDI/MDI projects.
 From the controls toolbox, choose the edit control and place it on a dialog box. In the properties
dialog of the edit control, enter the resource ID as IDC_EDTEST.
 If the edit control is supposed to accept only numbers, in the Edit control --> Properties -->
Styles tab, set the number property to true by checking the checkbox provided. This makes the
CEdit based edit control accept only numbers.
 Add a class member for the CEdit for the edit control. The code sample in this CEdit article
assumes the variable name to be m_Edit.
CEdit - Setting and Retrieving values:
The member functions of CEdit, CEdit .SetWindowText() and CEdit .GetWindowText() can be used to
set and get the values on the Edit control. The following is the code sample for setting the values in edit
controls.

//Set the value on CEdit


CString l_strValue = "Test Value to be set on CEdit";
m_Edit.SetWindowText(l_strValue);
//Get the value from the CEdit control
m_Edit.GetWindowText(l_strValue); //This gets the value into the CString variable l_strValue

CEdit - Using DDX mechanism:


Dynamic Data Exchange offered by MFC is a very useful feature, which allows programmers to ignore
the control variables and stick to value based variables. This is an easy way to initialize the values of
controls in a dialog box and to retrieve values from the controls. To enable the CEdit control for DDX
mechanism the following steps as outlined here may be performed.
 Open the Class Wizard.
 In the Member Variables tab, click Add Variable button.
 In the Add Member Variable dialog box, choose the Category as Value and choose the Variable
type as a suitable one. If the values can be manipulated are in character arrays, choose CString,
if numbers are going to be manipulated choose Number etc.,
 Click Ok and save the project. The control is now DDX enabled.
 The following code sample may be used for setting and getting the value on a DDX enabled
CEdit control. The sample assumes the variable name as m_strEdit.

//To set the value on a DDX based CEdit control


void DlgName::SetvalueonEdit()
{
UpdateData();
m_strEdit = "Test Value set for DDX";
UpdateData(FALSE);
}
//To get the value on a DDX based CEdit control
void DlgName::GetvalueFromEdit()
{
UpdateData();
CString strStoreValue;
strStoreValue = m_strEdit ;
UpdateData(FALSE);
}
Note: The CEdit control can also be set on a multi-line mode. While working on a multi-line mode the
CEdit will give some problems for using the function SetWindowText. The end of line characters won't be
shown properly. To solve this problem, for every end of line append the string with a "\r\n".
CComboBox Example
Combo box controls are space savers. Wherever there is no need for a multi-select from a list of items,
combo box is a good choice in such places. This article " CComboBox Example" explains how to use the
MFC CComboBox class for manipulation of a list of strings.

CComboBox Example - Initializing a Combo Box:


It is assumed that the readers of the sample have already created a dialog box (either in a dialog based
application or SDI/MDI application) and placed a combo box control from the controls toolbox on the
Resource Editor.
After placing the combo box control on the dialog box, open the class wizard by pressing Ctrl + W keys
or Menu --> View --> ClassWizard. In the Member Variables tab, Add a Variable for the CComboBox
class. This CComboBox example assumes that the variable name is,
CComboBox m_cbExample;
This m_cbExample will be used further in our CComboBox example MFC code.

CComboBox Example - Adding Items to a Combo Box:


The function AddString is used for adding items to a combo box. If there is a constant set of data, these
values can also be added in the Resource Editor itself. The Combo Box control properties dialog has a
tab for adding data. Otherwise the data can be added as follows.
m_cbExample.AddString("StringData1");
m_cbExample.AddString("StringData2");
m_cbExample.AddString("StringData3");

CComboBox Example - Retrieving Items from a Combo Box:


Usually a requirement for retrieving items from the combo box will arise from selecting the data. This
article also assumes the same. Now the data selected in a combo box needs to be retrieved.
To do this, the first step is to find out the index of the selected item inside the combo box control. Then
the item at the corresponding position needs to be pulled out as follows.
int nIndex = m_cbExample.GetCurSel();
CString strCBText;
m_cbExample.GetLBText( nIndex, strCBText);
In the above CComboBox example code, the value will be retrieved and stored in strCBText variable.
There is another overloaded version for GetLBText. But the version which uses CString is the easiest
one.

CComboBox Example - Finding Items inside a Combo Box:


This kind of Find operations on a Combo box will most probably be useful in programs that dynamically
modify the values in a combo box. The function FindStringExact is used to find the exact string match
inside a combo box.
int nIndex = m_cbExample.FindStringExact(0, "Value to be found");
The string position inside the combo box control is the return value. It returns CB_ERR if it was
unsuccessful in finding the string.
CComboBox Example - Deleting Items from a Combo Box:
This operation can be done by using the CCombobox member function DeleteString. This function
needs the index of the item inside the combo box.
m_cbExample.DeleteString(nIndex);

Potrebbero piacerti anche