Visual C++ and MFC Programming 2nd Edition

(Martin Jones) #1

Chapter 16: Text-Based Controls Visual C++ and MFC Fundamentals


applications, the OK object has a special meaning. To use an OK button, add a button to a
form and, from the ID combo box, select the IDOK identifier. What makes this constant
special is that the MFC library recognizes that, when the user clicks it, if the dialog box is
modal, the user is acknowledging the situation. If this dialog box was called from another
window using the DoModal() method, you can find out if the user had clicked OK and
then you can take further action. Therefore, when the user clicks OK, the dialog box calls
the OnOK() method. Its syntax is:

virtual void OnOK();

Although it looks like a simple method (and it is) the OnOK() method carries the
constant value IDOK that you can use as a return value of the DoModal() method.
Therefore, in one step, you can use the DoModal() method to display a modal dialog box
and find out whether the user clicked OK.

When a dialog box is equipped with an OK button, you should allow the user to press
Enter and perform the OK clicking. This is taken care of by setting the Default Button
property to True or checked.

The Cancel caption is useful on a button whose parent (the dialog box) would ask a
question or request a follow-up action from the user. A Cancel button is also easy to
create by simply adding a button to a dialog box and selecting IDCANCEL as its
identifier in the ID combo box. Setting a button's identifier to IDCANCEL also allows
the user to press Esc to dismiss the dialog box.

The scenarios described for the OK and the Cancel buttons are made possible only if the
compiler is able to check or validate the changes made on a dialog box. To make this
validation possible, in your class, you must overload the CWnd::DoDataExchange()
method. Its syntax is:

virtual void DoDataExchange( CDataExchange* pDX );

This method is used internally by the application (the framework) to find out if data on a
dialog box has been changed since the object was displayed. This method does two things
it ensure the exchange of data among controls and it validates the values of those
controls. In reality, it does not inherently perform data validation, meaning it would not
allow or disallow value on a control. Instead, the compiler uses it to create a table of the
controls on the dialog box, their variables and values, allowing other controls to refer to it
for data exchange and validating. If you want to find out the data a user would have typed
or selected in a control, you would have to write the necessary code.

By default, the caption on a button is positioned in the middle and the center of the
control. At design time, you can control this position using the Horizontal and the
Vertical Alignments on the Properties window:
Free download pdf