Getting edit box text from a modal MFC dialog afte

2020-06-23 09:35发布

问题:

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.

回答1:

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();


回答2:

  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



回答3:

DoModal() destroys the dialog box before it returns and so the value is no longer available.

It's hard to tell why you are setting m_pMainWnd to your dialog. To be honest, I'm not really sure what you are trying to do there. That's bound to cause problems as now AfxGetMainWnd() is broken.

Either way, you can't get the dialog box's control values after the dialog has been destroyed.



回答4:

I often use

D_SOHINH dsohinh = new D_SOHINH();
    dsohinh.vd_kichthuoc=v_kichthuocDOC;
    dsohinh.vd_sohinh=v_soluongDOC;
    if(dsohinh.DoModal()==IDOK)
    {
        v_soluongDOC=dsohinh.vd_sohinh;
        v_kichthuocDOC=dsohinh.vd_kichthuoc;
    }
    SetModifiedFlag(true);
    UpdateAllViews(NULL);

With dsohinh is Dialog form that you want to get data to mainform . After get data then call SetModifiedFlag(true) to set view data updated. call UpdateAllViews(NULL) to Set data to mainform