In part three of this ten part series, Mitchell talks about modal and modeless dialog boxes. "To create a fully interactive user experience, any application must employ some sort of dialog-based interaction. Dialog boxes come in two flavors: modal and modeless..."
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:
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
sentence = "This sentence was assigned in the OnInitDialog() function";
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:
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.