Using MFC in C++ Part 3: Dialog Boxes - The OnInitDialog() function
(Page 6 of 7 )
One last thing I would like to explain is the OnInitDialog() function of the CDialog class. Because our dialog box is derived from the CDialog class, it will also contain the OnInitDialog() function.
The OnInitDialog() function is called by C++ whenever a dialog box is initially instantiated, and usually contains variable declarations and assignments, which will be used by the dialog box during its life cycle.
Let’s override our dialog boxes OnInitDialog() function, just too see how it works. In main.h, change the CTestDialog’s class declaration to that shown below:
class CTestDialog : public CDialog
{
public:
CTestDialog() :
CDialog() {}
afx_msg void OnCancel();
afx_msg BOOL OnInitDialog();
afx_msg void OnLButtonDblClk(UINT flags, CPoint point);
CString sentence;
DECLARE_MESSAGE_MAP()
};As you can see, the OnInitDialog() function must return a Boolean value (true/false). It MUST return TRUE if the dialog box is to be created successfully. We have also overridden the OnLButtonDblClk() function, which is called whenever a double click is activated on the dialog. A new CString variable named sentence is also declared. Next, double-click on main.cpp, and add the following code just before the “CApp App;” line:
afx_msg BOOL CTestDialog::OnInitDialog()
{
// Call the base classes version
CDialog::OnInitDialog();
sentence = "This sentence was assigned in the OnInitDialog() function";
return TRUE;
}
afx_msg void CTestDialog::OnLButtonDblClk(UINT flags, CPoint point)
{
MessageBox(this->sentence);
}Lastly, we must tell windows that our CTestDialog() class will handle the OnLButtonDblClk() function, by changing its message map. Enter the following code between the BEGIN_MESSAGE_MAP(CTestDialog, CDialog) and END_MESSAGE_MAP() lines:
ON_WM_LBUTTONDBLCLK()We have just added the code for two of our overridden member functions, OnInitDialog() and OnLButtonDblClk(). In the OnInitDialog() function, we start by calling the base classes OnInitDialog() function. Next, we simply assign a value to the CString variable, sentence and return TRUE, indicating that the function succeeded.
The OnLButtonDblClk() function may be new to you. If it is, it’s really quite simple. It is the function that gets called whenever a double click is activated on a window. So, now, whenever you double-click on our modeless dialog box, a message box will appear. The message box will display the CString variable, sentence, which we declared in the OnInitDialog() function.

Of course, this is only an elementary example on the OnInitDialog() function, but it can also be used to call other functions, display other windows, etc.
Next: Conclusion >>
More C++ Articles
More By Mitchell Harper