Make Modal Dialogs Behave Like Modeless Dialogs

Environment: Visual C++ 4.0 (and above)

Description

This template class simulates the behaviour of a modeless dialog while allowing some of the programmatic control of a modal dialog. When modal dialog are closed control is immediately returned to the caller of the DoModal member function:
CMyDialog dlg;

if( dlg.DoModal() ) { ... }

However, the same can not be said of modal dialogs where the Create/ShowWindow member function pair need to be used in order to display the dialog.

CMyDialog dlg;
dlg.Create( IDD_MY_DIALOG );
dlg.ShowWindow();

...

if( you receive some message that the non-modal has closed ) 
{
...
}

The above code segment creates and activates a non-modal dialog. How and when you get control back generally involves some rather tricky programming - in other words, it's not nearly as straight-forward as using a modal dialog.

Usage

NonModalDialog<MyDlg>myDlg( AfxGetMainWnd() );
myDlg.DoModal();

...

class CWnd;

template <class ModalDialog>class NonModalDialog 
: public ModalDialog
{
public :
 NonModalDialog( CWnd *pParent ) 
 : ModalDialog( pParent ) { }

 virtual int DoModal();
 virtual void EndModalLoop( int );
protected:
 int m_nStillActive;
};

template <class ModalDialog>
inline int NonModalDialog<ModalDialog>::DoModal()
{
 MSG			l_objMessage;
 CWinThread*	l_pThread = AfxGetThread();

 ASSERT_VALID( l_pThread );

 Create( ModalDialog::IDD );	
 ShowWindow( SW_SHOW );
 m_nStillActive = 1;

 //--------- Thanks to Microsoft. This block 
 //--------- is from CWinThread::Run
 // from Thrdcore.cpp, with appropriate changes.
 ASSERT_VALID(this);
 // for tracking the idle time state
 BOOL l_nIdle = TRUE;
 LONG l_nIdleCount = 0;

 // acquire and dispatch messages until 
 // a WM_QUIT message is received,
 // or the dialog box is closed.
 for (;;) 
 {
  // phase1: check to see if we can do idle work
  while( l_nIdle && !::PeekMessage( &l_objMessage, 
                                    NULL, 
                                    NULL, 
                                    NULL, 
                                    PM_NOREMOVE ) ) 
  {
   // call OnIdle while in bIdle state
   if( !l_pThread->OnIdle( l_nIdleCount++ ) )
    l_nIdle = FALSE; // assume "no idle" state
  }
  
  // phase2: pump messages while available
  do 
  {
   // Relent control back to Windows if the dialog 
   // box has closed.
   if( !m_nStillActive )
    return m_nModalResult;

   if( l_objMessage.message == WM_SYSCOMMAND 
   && l_objMessage.wParam == SC_CLOSE )
    OnCancel();	// Close the dialog box first.

   // pump message, but quit on WM_QUIT
   if( !l_pThread->PumpMessage() )
    return l_pThread->ExitInstance();

   // reset "no idle" state after pumping 
   // "normal" message
   if( l_pThread->IsIdleMessage( &l_objMessage ) )
    l_nIdle = TRUE, l_nIdleCount = 0;
  } while( ::PeekMessage( &l_objMessage, 
                          NULL, 
                          NULL, 
                          NULL, 
                          PM_NOREMOVE ) );
 }
 ASSERT(FALSE);  // not reachable
 //---------------------
}

template <class ModalDialog>inline void 
NonModalDialog<ModalDialog>::EndModalLoop(int p_nResult)
{
 m_nStillActive = 0;
 ModalDialog::EndModalLoop( p_nResult );
}

Limitations

  1. Applies only to MFC versions that properly support OCX containment. ( v4.0 and later )
  2. From inside the dialog, you close it using EndDialog( ... ) only.
  3. You MUST take only two parameters, one is the IDD of your dialog, and the next is CWnd*, in your dialog's constructor.


Comments

  • You a saviour! Works perfectly!

    Posted by uNsignedINT on 12/07/2005 05:47am

    Hey! I have been looking for solutions to close a modeless dialog by clicking out side the dialog and with these functions I have solved the problem!! To close my dialog i've just implemented OnNcActivate and called EndDialog(). Thanks!!! :)

    Reply
  • Fix for bug with OnIdle()

    Posted by RobertWebb on 03/15/2005 02:08am

    This is a great little article. I noticed that OnIdle() didn't keep getting called though always. I don't really understand why exactly, but adding these lines:

    	nIdle = TRUE;
    	nIdleCount = 0;
    
    after the final "} while (::PeekMessage..." line fixed it. All the "normal" messages have been processed at that time, so it makes sense to me to return to idle processing. Thanks, Rob.

    Reply
  • Brilliant!! Works great. Just one recommendation.

    Posted by Axter on 01/27/2005 12:03pm

    I recommend you add a default value for the constructor, just as most windows class have default NULL values. Example: NonModalDialog( CWnd *pParent = NULL) : ModalDialog( pParent ) { } Otherwise, this class is PERFECT. I have to add it to my toolbox!!! Thanks!

    Reply
  • How to get WM_KICKIDLE message back in the dialog messages?

    Posted by Legacy on 09/10/2003 12:00am

    Originally posted by: Daniel

    When I use the NonModalDialog I can't use the mapped function of the message WM_KICKIDLE.

    How to solve this?

    Reply
  • how do i create a child dialog that will be displayed on the task bar???

    Posted by Legacy on 03/27/2003 12:00am

    Originally posted by: sriram


    your site is very userful to us..

    Reply
  • how do i create a child dialog that will be displayed on the task bar???

    Posted by Legacy on 03/27/2003 12:00am

    Originally posted by: sriram


    your site is very userful to us..

    Reply
  • How do I create a modeless dialog which can be destroyed by clicking any key down?

    Posted by Legacy on 04/23/2001 12:00am

    Originally posted by: ydong

    How do I create a modeless dialog which can be destroyed by clicking any key down (character keys, system keys and mouse keys), and the dialog without OK, Cancel and Close
    button?

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • "Security" is the number one issue holding business leaders back from the cloud. But does the reality match the perception? Keeping data close to home, on premises, makes business and IT leaders feel inherently more secure. But the truth is, cloud solutions can offer companies real, tangible security advantages. Before you assume that on-site is the only way to keep data safe, it's worth taking a comprehensive approach to evaluating risks. Doing so can lead to big benefits.

  • Hybrid cloud platforms need to think in terms of sweet spots when it comes to application platform interface (API) integration. Cloud Velocity has taken a unique approach to tight integration with the API sweet spot; enough to support the agility of physical and virtual apps, including multi-tier environments and databases, while reducing capital and operating costs. Read this case study to learn how a global-level Fortune 1000 company was able to deploy an entire 6+ TB Oracle eCommerce stack in Amazon Web …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds