Click here to Skip to main content
Click here to Skip to main content

Tutorial - Modeless Dialogs with MFC

, 18 Jun 2002 CPOL
Rate this:
Please Sign up or sign in to vote.
Some tips/suggestions on using modeless dialogs with MFC


Modeless dialog boxes have often puzzled newbie programmers. Basically a modeless dialog box is one that allows us to interact with other windows even when the modeless dialog is still on screen. If you keep in mind a few nifty little tricks then programming modeless dialogs will be a piece of cake.

Creating the modeless dialog

The straightforward way to create a modeless dialog is using Create(). Pass the name of the dialog's template resource and an optional CWnd* which points to the parent window. If you don't pass a parent window pointer the main application window will be used as the parent window. Create() will return true if the call was successful. 

Since Create() returns immediately unlike DoModal(), you must never declare your modeless dialog as a local variable with scope and lifetime only within the function where it is declared. Instead allocate the modeless dialog on the heap. If you don't do that, the modeless dialog will be destroyed the moment, you exit the function within which you declared it.

An alternative solution is to declare your modeless dialog as a heap member object of your main frame window or your CWinApp derived class. An advantage with this method is that you actually have control over the modeless dialog, since you have a pointer to it.

By the way, unlike modal dialogs, modeless dialogs need to have the WS_VISIBLE style set if you want them to be visible immediately after creation. Otherwise you'll have to explicitly call ShowWindow() with SW_SHOW. In fact I recommend that you do this, instead of going all over the place, changing default styles.

CModeLess *m_pmodeless = new CModeLess(this);

The parent issue

The usual practice is to make the parent window the main window of your application, which is typically the main frame window. Now one issue with this is that the modeless dialog will remain on top of this parent window. It allows you to interact with the main frame window, perhaps it contains a CView derived view. But it may be annoying and undesirable to have the modeless dialog remain on top. The solution here is to create the modeless dialog as a child of the desktop. Use GetDesktopWindow() to get a pointer to the Desktop and pass that as the parent window for the modeless dialog in your call to Create().


Destroying the modeless dialog

Since we have allocated memory on the heap, we must delete it when the modeless dialog is destroyed, otherwise we'll soon run into big trouble with memory leaking left, right and center. When the dialog is destroyed the last message our handler class receives is the WM_NCDESTROY message. The OnNcDestroy function is invoked and this in turns calls the virtual function PostNcDestroy. That's exactly where we can delete our modeless dialog. First call the base class function so that it does it's own cleaning up.

void CModeLess::PostNcDestroy() 
    delete this;

Issue with member objects

If the modeless dialog is a member object of the parent window class, we have a slight issue here. The member variable still holds a pointer reference, but the memory it references has been deleted. There are workarounds to this problem. One method is to post an user defined message to the parent window and handle it in the parent class, by setting the modeless dialog member variable to NULL. Another method is to use GetParent() to get the parent window, if any and then cast it to the actual parent class. Now we have access to the parent class's member variable that holds the pointer to the modeless dialog. Set that to NULL. The latter method is portrayed later where I discuss how to restrict a modeless dialog to one instance. The former method is shown below :-

void CModeLess::PostNcDestroy() 
    delete this;
LRESULT CMainFrame::OnMyMethod(WPARAM wParam, LPARAM lParam)
    m_pmodeless = NULL; 
    return 0;

Problems with OnOK() and OnCancel()

In modal dialog boxes, everybody including the queen's cook, has the OK/Cancel buttons. In my opinion, and presumably in many other more learned people's opinions, you'd do good to avoid having OK and Cancel on a modeless dialog. But if for some unavoidable reason, you badly want to have them on your modeless dialog, then you'll need to over-ride both functions.

Here is my modeless version of the OnCancel() function. As you can see I have simply called DestroyWindow() and I haven't bothered to call the base class. In fact don't call the base class at all. The base class function will call EndDialog() which is associated with DoModal().

void CModeLess::OnCancel() 

Okay, now for my modeless version of OnOK(). I have called DestroyWindow() as in the OnCancel(), but there is some extra code too as you can see. I am calling UpdateData, because that's what OnOK() does in a modal dialog. If the DDV macro validations are successful then UpdateData(true) returns true and we destroy the window, else the DDV message box is automatically shown to the user and we refuse to destroy the dialog. Thus we are simulating the behavior of a modal dialog's OK button here.

void CModeLess::OnOK() 


Passing back data

In modal dialogs, we can still access the data variables when DoModal() returns because the dialog object has not been destroyed yet, only the underlying dialog window has been destroyed. This is also possible with modeless dialogs using a nifty trick as shown below.

void CModeLess::OnOK() 


Here I have assigned the value of the dialog data variable m_sss to the parent class's member variable, m_x. Here, m_parent is a pointer to the parent window. If you are wondering where I got this m_parent from, scroll up and see how I have constructed my modeless dialog object. I'll repeat that single line to refresh your memory, and also to help you avoid scrolling, thus saving you some energy.

CModeLess *m_pmodeless = new CModeLess(this);

As you can see, I have passed this to the constructor. In my case, this is a pointer to my CFrameWnd derived class which App Wizard has named as CMainFrame for me. Now take a look at my CModeLess class's constructor.

CModeLess::CModeLess(CWnd* pParent /*=NULL*/)
    : CDialog(CModeLess::IDD, pParent)
    m_sss = 0;
    m_parent=pParent; //This is where I point m_parent to my main frame window

It all slowly makes sense, eh?

Tracking the modeless dialog count

Let's say you want to have only one instance of the modeless dialog alive at one time. In that case, each time the user initiates some action that results in the bringing up of the modeless dialog you have to check and see if the modeless dialog is already active. Say, m_pmodeless is the modeless dialog member of your class. In the class constructor set m_pmodeless to NULL. Now each time you check to see if m_pmodeless  is NULL and if it is NULL, create a new modeless dialog, otherwise, show a MessageBox that the dialog is already active or use SetForegroundWindow() to bring the modeless dialog to the foreground..

Here is how I create my modeless dialog now that I want to restrict them to just one at a time:-

    m_pmodeless = new CModeLess(this);

But when the dialog is destroyed we need to inform the parent class that the pointer it holds is now useless. What we do is to set that pointer to NULL in the PostNcDestroy. In fact it is essential that you do this, otherwise the next time the user tries to activate the modeless dialog, your program will crash as it thinks m_pmodeless is still pointing to a valid dialog window and tried to call SetForegroundWindow() on it. And here is my PostNcDestroy :-

void CModeLess::PostNcDestroy() 
    ((CMainFrame*)m_parent)->m_pmodeless = NULL;
    delete this;


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Nish Nishant

United States United States
Nish is a real nice guy who has been writing code since 1990 when he first got his hands on an 8088 with 640 KB RAM. Originally from sunny Trivandrum in India, he has been living in various places over the past few years and often thinks it’s time he settled down somewhere.
Nish has been a Microsoft Visual C++ MVP since October, 2002 - awfully nice of Microsoft, he thinks. He maintains an MVP tips and tricks web site - where you can find a consolidated list of his articles, writings and ideas on VC++, MFC, .NET and C++/CLI. Oh, and you might want to check out his blog on C++/CLI, MFC, .NET and a lot of other stuff -
Nish loves reading Science Fiction, P G Wodehouse and Agatha Christie, and also fancies himself to be a decent writer of sorts. He has authored a romantic comedy Summer Love and Some more Cricket as well as a programming book – Extending MFC applications with the .NET Framework.
Nish's latest book C++/CLI in Action published by Manning Publications is now available for purchase. You can read more about the book on his blog.
Despite his wife's attempts to get him into cooking, his best effort so far has been a badly done omelette. Some day, he hopes to be a good cook, and to cook a tasty dinner for his wife.

Comments and Discussions

QuestionModeless Dialog Object within CView Object [modified] PinmemberMember 1062166724-Feb-14 7:13 
AnswerRe: Modeless Dialog Object within CView Object PinmemberMember 1062166728-Feb-14 9:21 
GeneralMy vote of 5 PinmemberMyCodeWorks19-Jun-13 3:56 
GeneralMy vote of 5 Pinmemberkanalbrummer14-Jun-13 4:45 
GeneralRe: My vote of 5 PinsitebuilderNish Sivakumar14-Jun-13 5:15 
QuestionProblem with Grandchildren Pinmemberandywebsdale31-Dec-12 8:46 
QuestionMemory Leak PinmemberJasonDiplomat20-Jul-12 8:45 
GeneralMy vote of 5 PinmemberAndrei Bozantan13-Jul-11 2:06 
AnswerRe: My vote of 5 PinmvpNishant Sivakumar24-Oct-11 9:10 
GeneralThe opposite of time waster is... [modified] PinsubeditorIndivara5-Dec-10 21:17 
GeneralRe: The opposite of time waster is... PinmvpNishant Sivakumar6-Dec-10 7:16 
GeneralMy vote of 5 PinmemberThomas Haase13-Aug-10 1:59 
AnswerRe: My vote of 5 PinmvpNishant Sivakumar24-Oct-11 9:09 
Generalpass data Pinmemberjc_225912-Jul-10 0:19 
this is very helpful.
How do I pass data to the modeless dialog?
Generalthis is very helpful PinmemberCharvak Karpe21-May-10 14:21 
Generalthanks... but i have a question.. PinmemberVirex_A12-Nov-08 22:30 
GeneralModeless dialog not showing the fields Pinmemberpvasanthi9-Jul-07 3:09 
GeneralRe: Modeless dialog not showing the fields PinmemberSpjoiing2-Jul-10 3:58 
QuestionRe: Modeless dialog not showing the fields Pinmemberp.divya1126-May-11 7:40 
QuestionStorage of Modeless dialog is it in Heap /Stack PinmemberPrabodh Kumar Panda18-Jun-07 22:57 
AnswerRe: Storage of Modeless dialog is it in Heap /Stack PinmvpNishant Sivakumar24-Oct-11 9:09 
GeneralNice, but not the easiest method PinmemberMubeen_D29-Nov-06 7:34 
GeneralRe: Nice, but not the easiest method [modified] Pinmemberrbid14-Sep-08 3:37 
QuestionGetDesktopWindow Pinmembereusto11-Jul-06 1:11 
QuestionHow to change parent of dialog wthout destroy Pinmembersrikanth_shettigar22-May-06 3:54 
GeneralDemo will not complie Pinmemberdoctorrie22-Apr-06 20:46 
QuestionDo you have any suggestion? PinmemberHongjun Ge21-Apr-06 5:05 
QuestionHow to put image into modelss dialog PinmemberHaiau2271-Mar-06 9:51 
QuestionProblems with Modal Parent of Modeless Pinmemberjmmartin15-Feb-06 19:13 
GeneralWhy error in EVC PinmemberFlyingDancer4-Jan-06 21:33 
GeneralAny idea to update CEdit in dlg class form non MFC Class Pinmembervictoryelectorn12-Dec-05 21:18 
GeneralIn MFC modeless dialog PretranslateMessage is never reached PinmemberSophieMrc16-Jun-05 5:20 
GeneralRe: In MFC modeless dialog PretranslateMessage is never reached PinmemberTPayne1-Sep-05 15:57 
QuestionRe: In MFC modeless dialog PretranslateMessage is never reached Pinmemberddas7727-Nov-06 22:59 
AnswerRe: In MFC modeless dialog PretranslateMessage is never reached Pinmembernumfive13-Jan-11 23:11 
GeneralRe: In MFC modeless dialog PretranslateMessage is never reached Pinmembergordon889-Sep-11 1:31 
GeneralGetParent: CView and modeless dlg PinmemberRichard.P.Jones28-Mar-05 11:11 
AnswerRe: GetParent: CView and modeless dlg Pinmemberrodel.ros13-Sep-06 3:51 
GeneralProgress Bar in Modeless Dialog PinmemberMadhu Reddy27-Feb-05 19:13 
GeneralGetParent() failes due to NULL m_hWnd PinsussAnonymous7-Dec-04 2:35 
GeneralModeless dialogs PinsussAnonymous4-Sep-04 11:22 
GeneralPassing back data Pinmembercim@szm.sk2-Sep-04 22:11 
GeneralCenterWindow() Pinmembercim@szm.sk2-Sep-04 21:38 
QuestionTrue ModeLess? Pinmembertyramanan22-Jul-04 22:05 
AnswerRe: True ModeLess? PinmemberVarchas23-Jul-04 1:39 
GeneralRe: True ModeLess? Pinmembertyramanan5-Aug-04 19:29 
GeneralError when using GetDesktopWindow() PinmemberRodney Elliott20-Jul-04 15:01 
Questionwhat if i want to have many instances.. Pinmemberkfaday1-Jun-04 9:31 
AnswerRe: what if i want to have many instances.. Pinmemberrodel.ros13-Sep-06 3:46 
GeneralVery nice!!! Pinmembereb300024-May-04 0:45 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150327.1 | Last Updated 19 Jun 2002
Article Copyright 2001 by Nish Nishant
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid