Using MFC in C++ Part 3: Dialog Boxes - Creating a modeless dialog box
(Page 5 of 7 )
A modeless dialog box is a dialog that is separate from any other dialog/window. It has an optional parent window, and can be activated from any dialog/window in our application. Because of this, a modeless dialog box needs more code than a modal dialog box to create and interact with it. To create a modeless dialog box, we simply make a few modifications to our current modal dialog box application.
Firstly, because a modeless dialog box doesn’t have a parent window, it will need to be decelerated as a global object. Whenever a modeless dialog box goes out of scope, the CDialogs destructor will automatically call DestroyWindow(), which will destroy it.
Secondly, instead of calling the DoModal() function to activate the dialog box, we will call the CDialog()’s Create() function.
Thirdly, we must keep track of whether or not the modeless dialog box is “active”. If it is, and we try to instantiate it again, we will get an error. We will use a variable to track whether it is active or not.
Double click on main.cpp, and add the following code after the last #include line:
CTestDialog testDlg;
BOOL dlgVisible = FALSE;Next, we will need to modify the constructor of our CTestDialog() class, like this:
class CTestDialog : public CDialog
{
public:
CTestDialog() :
CDialog() {}
DECLARE_MESSAGE_MAP()
};
Lastly, we modify the CMainWin::OnShowDialog() function:
afx_msg void CMainWin::OnShowDialog()
{
if(!dlgVisible)
{
testDlg.Create("TestDialog", this);
dlgVisible = TRUE;
}
}Now, compile and run your program. Choose the “Show Dialog” menu option. The modeless dialog box will appear. Instead of being solely confined to that dialog, however, you can also maximize the main window, move it around, etc.
Notice though, that when you close the modeless dialog box, you can’t open it again. That’s because C++ is calling the modeless dialog boxes OnCancel() event. In order to set our dlgVisible variable back to false (So the dialog will be displayed if we choose the menu option again), we must override the dialogs OnCancel() member function.
The OnCancel member functions prototype is shown below:
afx_msg void OnCancel();In main.h, just before the DECLARE_MESSAGE_MAP() line, enter the following line:
afx_msg void OnCancel();Next, in main.cpp, we will create the overridden function declaration. Enter the following code just before the “CApp App;” line:
afx_msg void CTestDialog::OnCancel()
{
dlgVisible = FALSE;
DestroyWindow();
}Notice that the CTestDialog::OnCancel() member function makes a call to the DestroyWindow() function? This function is derived from our base class, CDialog, and physically removes the dialog box from our application.
Once again, compile and run your program. Notice now, that you can show the dialog box, hide it, and then show it again.
Next: The OnInitDialog() function >>
More C++ Articles
More By Mitchell Harper