如何在两个对话框之间发送全局值

时间:2013-06-21 07:24:34

标签: mfc struct dialog

目前,我在两个对话框中有两个结构,如下所示

GetDialog.h
struct GetDlgData{
int     nStatic1;
int     nStatic2;
CString strEdit1;   
CString strEdit2;       
};
GetDlgData g_structData;
CStatic m_staticGet1;
CStatic m_staticGet2;
CEdit m_editGet1;
CEdit m_editGet2;
void SetGetValue();
GetDlgData GetGetValue(){return g_structData;}
virtual BOOL OnInitDialog();

DoModalGetDataDlg.h
struct DoData {
  int   nStatic1;
  int   nStatic2;
  CString strEdit1; 
  CString strEdit2;     
};
CStatic m_staticDo1;
CStatic m_staticDo2;
CEdit m_editDo1;
CEdit m_editDo2;
DoData g_structData;
void SetDoValue();  
DoData GetDoValue() { return g_structData;}
afx_msg void OnBnClickedButtonDo();

我希望将值发送到另一个对话框,该对话框保存在struct

DoModalGetDataDlg.cpp
void CDoModalGetDataDlg::SetDoValue()
{
CString strTemp;

strTemp.Empty();
m_staticDo1.GetWindowText(strTemp);
g_structData.nStatic1 = _ttoi(strTemp);

strTemp.Empty();
m_staticDo2.GetWindowText(strTemp);
g_structData.nStatic2 = _ttoi(strTemp);

m_editDo1.GetWindowText(g_structData.strEdit1);

m_editDo2.GetWindowText(g_structData.strEdit2);
}

void CDoModalGetDataDlg::OnBnClickedButtonDo()
{
DoData structData;
SetDoValue();

CGetDialog GetDlg;
GetDlg.DoModal();
}

在对话框init

中获取GetDlg.cpp中的数据
BOOL CGetDialog::OnInitDialog()
{
CDialog::OnInitDialog();
SetGetValue();

return TRUE;  // return TRUE unless you set the focus to a control
}

void CGetDialog::SetGetValue()
{
 CDoModalGetDataDlg DoDlg(AfxGetMainWnd());
 memcpy(&g_structData, &DoDlg.GetDoValue(), sizeof(GetDlgData));

 CString strTemp;
 strTemp.Empty();
 strTemp.Format(_T("%d"), g_structData.nStatic1);
 m_staticGet1.SetWindowText(strTemp);

 strTemp.Empty();
 strTemp.Format(_T("%d"), g_structData.nStatic2);
 m_staticGet2.SetWindowText(strTemp);

 m_editGet1.SetWindowText(g_structData.strEdit1);

 m_editGet2.SetWindowText(g_structData.strEdit2);
}

但值在memcpy区域是随机的。我该如何解决...

非常感谢!

1 个答案:

答案 0 :(得分:0)

您对CDoModalGetDataDlg DoDlg(AfxGetMainWnd());的来电会创建CDoModalGetDataDlg的新实例,而不是" connect"到该类的现有实例。

您可以在调用DoModal()之前设置值,例如

void CDoModalGetDataDlg::OnBnClickedButtonDo()
{   DoData structData;
    SetDoValue();

    CGetDialog GetDlg;
    memcpy(&GetDlg.g_structData, &GetDoValue(), sizeof(GetDlgData));
    GetDlg.DoModal();
}