Dialog - worked example
key : purple - original code / blue - new code
Step 1 :
Create a new project using the MFC AppWizard(exe) (this worked example is based on a program which was called names). Select Multi Document Application at Step 1 of the Wizard. This is not necessarry for this program but it is essential for later developments.
Step 2 :
Using ClassWizard add the following (protected) member variables to the Document :
CString m_strFirstName;
CString m_strSecondName;
Step 3 :
These variables may be initialised in the Document's constructor :
CNamesDoc::CNamesDoc()
{
m_strFirstName = "";
m_strSecondName = "";
}
Step 4 :
Using the ClassWizard add the following (public) member functions to the Document :
void
CNamesDoc::SetFirstName(const CString &strFirstName)
{
m_strFirstName = strFirstName;
}
void
CNamesDoc::SetSecondName(const CString &strSecondName)
{
m_strSecondName = strSecondName;
}
CString
CNamesDoc::GetFirstName()
{
return m_strFirstName;
}
CString
CNamesDoc::GetSecondName()
{
return m_strSecondName;
}
Step 5 :
In the Resource View open the menu folder followed by the NAMESTYPE menu bar. Create a menu item called "Enter Names" - give this the identity "ID_ENTERNAMES". Open the ClassWizard and attach an event handler to this ID in the View. This is automatically called OnEnterNames().
Step 6 :
Remaining in the Resource View create a new dialog within the dialog folder. This will be a new class - a sensible identity would be ID_ENTER_NAMES_DLG and a suggested class name would be CEnterNamesDlg.
This dialog box should have two edit boxes for the user to enter the first and second names. An OK and a cancel button are provided by the compiler. Change the ID of each edit box for clarity (ie IDC_FIRST_NAME and IDC_SECOND_NAME). Using ClassWizard add member variables (CString m_strFirstName to the first edit box and CString m_strSecondName to the second edit box).
*Remember to inform the Document about this new class*
Step 7 :
Go to the OnEnterNames() function created in Step 5 and add the following code :
void
CNamesView::OnEnterNames()
{
GetDocument()->AddNames();
Invalidate();
}
Step 8 :
Add an AddNames() function to the Document :
void
CNamesDoc::AddNames()
{
CEnterNamesDlg dlg;
if(dlg.DoModal() == IDOK)
{m_strFirstName = dlg.m_strFirstName;
m_strSecondName = dlg.m_strSecondName;}
}
Step 9 :
Edit the OnDraw() function within the View :
void
CNamesView::OnDraw(CDC* pDC)
{
CNamesDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
// TODO: add draw code for native data here
pDC->TextOut(0, 0, pDoc->GetFirstName() + " " + pDoc->GetSecondName());
}
Click here for the basic exercise
Click here for the source code
Click here to return to menu