非模态对话框的创建及使用

来自:https://blog.csdn.net/s634772208/article/details/46404761?utm_source=blogxgwz4

 

在开始本文之前,假设我已经派生了一个对话框类CMyDlg。 
对于模态对话框,使用非常简单,通常会像以下这样使用: 
void Fun() 

        ............... 
        CMyDlg mydlg; 
        mydlg.DoModal(); 
        ................ 


而对于非模态对话框,通常会像以下这样使用 
void Fun() 

        ............... 
        CMyDlg*  pMydlg = new CMyDlg; 
        pMydlg->Create( IDC_MY_DLG ); 
        pMydlg->ShowWindow( SW_SHOW ); 
        ................ 

因为非模态对话框是new出来的,所以要释放对象。 
微软的建议是: 

A modal dialog box closes automatically when the user presses the OK or Cancel buttons or when your code calls theEndDialog member function.

When you implement a modeless dialog box, always override the OnCancel member function and call DestroyWindow from within it. Don’t call the base class CDialog::OnCancel, because it calls EndDialog, which will make the dialog box invisible but will not destroy it. You should also override PostNcDestroy for modeless dialog boxes in order to delete this, since modeless dialog boxes are usually allocated with new. Modal dialog boxes are usually constructed on the frame and do not need PostNcDestroy cleanup.

所以我们也按照他们的建议进行操作,

 

  1.  void CMyDlg::OnOK()
  2.  {
  3.  // TODO: 在此添加专用代码和/或调用基类
  4.  DestroyWindow();
  5.   
  6.  return;
  7.  //CDialogEx::OnOK(); 
  8. }
  9.   
  10.  
  11.   
  12.  void CMyDlg::OnCancel()
  13.  {
  14.  // TODO: 在此添加专用代码和/或调用基类
  15.  
  16.  DestroyWindow();
  17.   
  18.  return;
  19.  //CDialogEx::OnCancel();
  20.  }
  21.   
  22.   
  23.  void CMyDlg::PostNcDestroy()
  24.  {
  25.  // TODO: 在此添加专用代码和/或调用基类
  26.  CDialogEx::PostNcDestroy();
  27.   
  28.  delete this;
  29.  }


注:如果你不是像以上那样临时new一个的话,比如你可能会让它成为一个类成员对象,然后在初始化的时间创建它,在类销毁时自动销毁此模态对话框的话,那么就不应该在PostNcDestroy处delete它,也不应当DestroyWindow()它,会引发内存操作错误。因为此时它并不是new出来的。比如:在类A中有一个成员变量为CMyDlg m_mMyDlg;  然后在类构造函数中调用m_mMyDlg.Create( IDC_MY_DLG); 

作者:山丘儿
转载请标明出处,谢谢。原文地址:http://blog.csdn.net/s634772208/article/details/46404761

posted @ 2020-12-13 23:01  宇宙之外  阅读(500)  评论(0编辑  收藏  举报