Using a Dialog Box as a Main Window

Although it is possible to fill a standard frame window with one or more child control windows to imitate the look of a dialog box, using a real dialog window gives you access to extra functionality, such as allowing the user to move between controls with the TAB key, that is not easily available in a standard frame window. In addition, when you use a dialog window, many operations on child control windows, such as getting the text from an edit text control, are simplified. Thus, it is sometimes desirable to use a dialog window as the main window of your application.

As described in the “Cookbook” section on instance initialization, you typically create your main application window in the InitInstance function of CWinApp. When you are using a standard frame window, you create the window and assign it to the m_pMainWnd member variable of the application object. When you are using a dialog window as the main window, you still create the dialog window in InitInstance just as you would for a normal frame window.

·To use a dialog box as the main window:

1.Derive your main window from CDialog.

At least one of its message-handler functions should call the PostQuitMessage function to signal that the user wishes to quit the program. A typical way to do this is to use the WS_SYSMENU style in the dialog template and handle the WM_CLOSE message from the Control menu to call PostQuitMessage.

The following resource definition, class declaration, and message-map definition show how this strategy could be implemented.

main DIALOG 22, 17, 250, 120

STYLE WS_DLGFRAME | WS_CAPTION | WS_SYSMENU

CAPTION "Dialog Title"

BEGIN

/* control definitions go here ...*/

END

class CMainDlgWindow : public CDialog

{

public:

CMainDlgWindow()

{

Create( "main" );

}

afx_msg void OnClose()

{

PostQuitMessage( 0 );

}

DECLARE_MESSAGE_MAP()

};

// in .CPP file

BEGIN_MESSAGE_MAP( CMainDlgWindow, CDialog )

ON_WM_CLOSE()

END_MESSAGE_MAP()

2.Create the dialog box in your application's overriding InitInstance function:

BOOL CMyApp::InitInstance()

{

m_pMainWnd = new CMainDlgWindow();

m_pMainWnd->ShowWindow( m_nCmdShow );

m_pMainWnd->UpdateWindow();

return TRUE;

}

Your dialog might also have a Quit button, in which case the message-handler function for the BN_CLICKED message from that button would also call PostQuitMessage.