15.2 Using Microsoft Foundation Control Classes

The Microsoft Foundation Class Library provides a set of classes that correspond to the standard Windows control windows, such as buttons, edit text controls, and scroll bars. You can use these control classes in any situation where you would normally use a Windows control.

The following list shows the Microsoft Foundation control classes and the corresponding Windows controls:

Foundation class Windows control

CStatic Static control
CButton Button control
CListBox List box control
CComboBox Combo box control
CEdit Edit control
CScrollBar Scroll bar control

The Microsoft Foundation control classes require two-stage contruction. That is, you first allocate the object and then call a separate initialization function (named Create) to create the Windows control and attach it to the Foundation control object. You must call Create on a Foundation control object before calling any other member functions for the object.

·To create a standard Microsoft Foundation control object:

1.Allocate a control object, either by

Defining it on the frame, or by

Calling the new operator.

2.Call the Create function for the object, supplying the necessary arguments to create the corresponding Windows control window and attach it to the Microsoft Foundation control object.

The following code shows how you might declare a CEdit object in the class declaration of your derived dialog class, and then call the Create member function in OnInitDialog function. Because the CEdit object is declared as an embedded object (not as a pointer) it is automatically allocated when the dialog object is contructed. Although the CEdit object is constructed at the same time as the dialog, it must still be initialized with the Create member function.

class CMyDialog : public CDialog { protected: CEdit m_edit; public: virtualBOOL OnInitDialog(); };

The OnInitDialog function sets up a rectangle, and then calls Create to create the Windows edit control and attach it to the uninitialized CEdit object. After creating the edit control, you can also set the input focus to the control by calling the SetFocus member function. Finally, you return FALSE from OnInitDialog to show that you set the focus. If you return TRUE, the dialog manager will set the focus to the first control item in the dialog item list.

BOOL CMyDialog::OnInitDialog()

{

RECT r;

r.top = 85;

r.bottom = 110;

r.left = 180;

r.right = 210;

m_edit.Create( WS_CHILD | WS_VISIBLE | WS_TABSTOP |

ES_AUTOHSCROLL | WS_BORDER,

r,

this,

ID_EXTRA_EDIT);

// set input focus to new edit control

m_edit.SetFocus();

// return FALSE only if you have set the focus

return FALSE;

}