How to get a value from an MFC dialog box
May 23rd, 2006
This may cause experience MFC developers to laugh but for a part-time MFC dabbler like me, it was quite frustrating to simple get a value entered into a dialog box..
To recap, once you have created a dialog box you the display it by using the stock-standard doModal call:
CMyDialogClass myDialog;
int nResponse = myDialog.DoModal();
if (nResponse == IDOK)
{
// TODO: Place code here to handle when the dialog is dismissed with OK
}
else if (nResponse =IDCANCEL)
{
// TODO: Place code here to handle when the dialog is dismissed with Cancel
}
This is all well and dandy but how do I now get the value of an edit control from the dialog box? Remember that once DoModal has finished, the dialog window no longer exists and we can't get values from the Window. I found some really complicated stuff about sending and intercepting Windows messages but the answer, or at least my answer, was very simple.
Yes the dialog window has gone but the dialog class remains ! So we simply get the dialog save the value of the edit box to a Public member variable and then get the value from that variable after the dialog has closed.
This is the code for the dialog box containing the Edit Control. This code is tied to the button click event of the Ok button.
void CMyDialog::OnOK()
{
m_Edit_Control.GetWindowText(g_csEditValue);
CDialog::OnOK();
}
So all we do here is get the value of the edit control and save it to a global var.
Then the code to call the dialog box becomes:
CMyDialogClass myDialog;
int nResponse = myDialog.DoModal();
if (nResponse == IDOK){
CString csTemp = MyDialog.g_csEditValue // store the value from the edit control
}else if (nResponse =IDCANCEL){
}
This is so simple when you look at it but I still couldn't find an example out there on the web. Enjoy !