Setting up a new document in MFC

When a user creates a new document in my SDI application, I need to present a dialog with details in the document being created (think: resolution, bit-depth, etc.). I first posted the code to display this dialog in OnNewDocument () (I don't need this when opening an existing document), but putting UI code into the document class just doesn't seem right (also I don't have a CWnd * to use as a parent dialog). Is there a better place for this in MFC?

0


a source to share


1 answer


You are correct, the document class is not suitable for the user interface.

CDocTemplate::[OpenDocumentFile][1](pszPath)

looks like a better candidate:

pszPath == NULL means "create a new document".

Method is virtual -> just infer CMySingleDocTemplate

from CSingleDocTemplate

and use an instance of that class inCMyWinApp::InitInstance().

This class is responsible for creating documents, frames and views, so I find it a good place to install a UI.



BOOL CMyWinApp::InitInstance()
{
  ...
  CSingleDocTemplate* pDocTemplate;
  pDocTemplate = new CMySingleDocTemplate( // <--Derives from CSingleDocTemplate
    IDR_MAINFRAME,
    RUNTIME_CLASS(CMyDoc),
    RUNTIME_CLASS(CMainFrame),
    RUNTIME_CLASS(CMyView));
  AddDocTemplate(pDocTemplate);
  ...
}

CDocument* CMySingleDocTemplate::OpenDocumentFile(LPCTSTR lpszPathName,
    BOOL bMakeVisible)
{
  CDocument *pDoc = 
    CSingleDocTemplate::OpenDocumentFile(lpszPathName, bMakeVisible);

  if (lpszPathName==NULL)
  {
    // GUI to get user info

    // update doc
    m_pOnlyDoc->Blah(input);

    // update view
    m_pOnlyDoc->UpdateAllViews(NULL,...,...);
  }
}

      

This may not be ideal: SDI has one and only doc object. It is reused in File / Load and File / New operations.

This function will be called the first time before the main mainframe is created. You might not want the dialog to be presented to the user before the frame is created. Oh! It's a little more complicated: Instead of embedding the GUI in the OpenDocumentFile (NULL) as above, just send a custom message / command to the main frame. Then add a handler that will respond to the sequence displaying GUI / update doc / update plots. This way the main frame will be displayed before the GUI appears and your user will be happier.

This also solves your problem when you don't have a CWnd parent: the main frame has already been created and your dialog will use it by default.

BTW, another solution is to add a command handler for ID_FILE_NEW in your CMyWinApp messagemap and add your own OnFileNew () override. But when you write OnFileNew (), I believe you will quickly find out that this is an ugly solution :-(

+2


a source







All Articles