关闭模式 MFC 对话框后获取编辑框文本

2022-01-12 00:00:00 visual-c++ modal-dialog mfc

从模态 MFC 对话框中,我想在对话框关闭后从编辑框中提取文本.我试过这个:

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;

它不起作用.

推荐答案

在调用 DoModal() 之前不会创建对话框及其控件,并且如前所述,在 DoModal() 返回时已经销毁.因此,您既不能在 DoModal() 之前也不能在之后调用 GetDlgItem().将数据传递或检索到控件的解决方案是使用类中的变量.您可以在创建类实例时,在调用 DoModal() 之前设置它.在 OnInitDialog() 中,您将变量的值放入控件中.然后,当窗口被销毁时,您从控件中获取值并将其放入变量中.然后从调用上下文中读取变量.

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

相关文章