|
-
December 20th, 2006, 04:53 AM
#1
How to destroy a window on the heap correctly?
I create a modeless dialog by using new operator during the application is runing. And I want to destroy it until the user quit the application.
But this window is destroyed automatically by MFC,and if call DestroyWindow somewhere an error will occur.
Code:
CMyDialog::PostNcDestroy()
{
// this will be called by the frame firstly!
CDialog::PostNcDestroy();
delete this;
}
CMyView::OnCreateDialog()
{
if(m_pDlg==NULL)
{
m_pDlg=new CMyDialog;
m_pDlg->Create(IDD_MYDIALOG);
m_pDlg->ShowWindow(SW_SHOW);
}
}
CMyView::OnDsetroy()
{
//this call will be " Unhandled exception" error
if(m_pDlg!=NULL) m_pDlg->DestroyWindow();
}
Of course, if cancel the code below:
Code:
//if(m_pDlg!=NULL) m_pDlg->DestroyWindow();
there will be nothing error.
But I don't want the frame do free work for me.
I prefer that all the resource allocated by myslef is freed by myself also.
So how to destroy the dialog correctly?
Thanks!
-
December 20th, 2006, 05:36 AM
#2
Re: How to destroy a window on the heap correctly?
1. I think there is no need to create a dialog object by new, why not just to declare a varialbe, then when you don't need the dialog anymore just call DestroyWindow().
2. Also, I think the problem is in the `delete this' in member function, guess you're calling some member function implicitly/explicitly through the pointer to the dialog (which is of course not valid already), thats why getting an error.
-
December 20th, 2006, 09:36 PM
#3
Re: How to destroy a window on the heap correctly?
Thanks for your advise.
Actually I want to know how do MFC destroy child window when the app is quitting.If the dialog's parent is main app window or client window. Is there anything difference?
-
December 21st, 2006, 03:43 AM
#4
Re: How to destroy a window on the heap correctly?
Actually MFC doesn't destroy windows as well as it doesn't create them by new-operator. When application gets closed all windows receive WM_CLOSE message, and their correspondent handlers make some work. After WM_CLOSE wnidow receives sequentially WM_DESTROY, WM_NCDESTROY and after that the kernel destroys window object. Please, have in mind - the window kernel object and MFC C++ object are absolutely different and independent from each other. Therefore the window object can be destroyed, but C++ object can stay alive. Trying to eliminate this situation the base WM_NCDESTROY handling (which triggers PostNcDestroy) typically result in calling delete this. If you want this effect off, you override PostNcDestroy in your window class where you merely omit calling delete this.
Last edited by Igor Vartanov; December 21st, 2006 at 03:46 AM.
Best regards,
Igor
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|