Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting edit box text from a modal MFC dialog after it is closed

From a modal MFC dialog, I want to extract text from an edit box after the dialog is closed. I attempted this:

CPreparationDlg Dlg;
CString m_str;

m_pMainWnd = &Dlg;
Dlg.DoModal();
CWnd *pMyDialog=AfxGetMainWnd();
CWnd *pWnd=pMyDialog->GetDlgItem(IDC_EDIT1);
pWnd->SetWindowText("huha max");
return TRUE;

It does not work.

like image 996
abhinav Avatar asked Nov 29 '22 18:11

abhinav


2 Answers

The dialog and its controls is not created until you call DoModal() and as already pointed, is destroyed already by the time DoModal() returns. Because of that you cannot call GetDlgItem() neither before, nor after DoModal(). The solution to pass or retrieve data to a control, is to use a variable in the class. You can set it when you create the class instance, before the call to DoModal(). In OnInitDialog() you put in the control the value of the variable. Then, when the window is destroyed, you get the value from the control and put it into the variable. Then you read the variable from the calling context.

Something like this (notice I typed it directly in the browser, so there might be errors):

class CMyDialog : CDialog
{
  CString m_value;
public:  
  CString GetValue() const {return m_value;}
  void SetValue(const CString& value) {m_value = value;}

  virtual BOOL OnInitDialog();
  virtual BOOL DestroyWindow( );
}

BOOL CMyDialog::OnInitDialog()
{
  CDialog::OnInitDialog();

  SetDlgItemText(IDC_EDIT1, m_value);

  return TRUE;
}

BOOL CMyDialog::DestroyWindow()
{
  GetDlgItemText(IDC_EDIT1, m_value);

  return CDialog::DestroyWindow();
}

Then you can use it like this:

CMyDialog dlg;

dlg.SetValue("stackoverflow");

dlg.DoModal();

CString response = dlg.GetValue();
like image 96
Marius Bancila Avatar answered Dec 05 '22 07:12

Marius Bancila


  1. Open your dialog resource, right-click on the textbox and choose "Add variable", pick value-type and CString
  2. In the dialog-class: before closing, call UpdateData(TRUE)
  3. Outside the dialog:

    CPreparationDlg dlg(AfxGetMainWnd());
    
    dlg.m_myVariableName = "my Value"; 
    
    dlg.DoModal();
    

    // the new value is still in dlg.m_myVariableName

like image 39
dwo Avatar answered Dec 05 '22 06:12

dwo