ATL CWindow class has a useful virtual method OnFinalMessage which is called after the last window message for the window is processed – at this point it is safe to destroy or deleted any objects associated with the window. Is there any equivalent for windows derived from the MFC CWnd class?
ATL CWindow class has a useful virtual method OnFinalMessage which is called after the
Share
This answer describes how I eventually solved my problem. I’ll note that while the answer by John Dibling was helpful, this was not the final solution to my problem. This is because the WM_NC_DESTROY message is sent as the final message to the window, but this can be handled before the last message to the window has finished being handled. See for example http://support.microsoft.com/?kbid=202110 for an explanation of the problem.
After having called
delete this, the object is no longer valid, but you are still technically in theWM_CLOSEhandler so you will probably crash when you eventually get back there. This means it is not really safe to assume that you can dodelete thisin PostNcDestroy, since the object may still be live in some other stack frame.I created the above class, note that it is derived from the ATL CWindow class – this allows me to use the OnFinalMessage handler for this class. The OnFinalMessage handler is different from the PostNcDestroy in MFC windows in that it is guaranteed to be called only after the final message handler on the stack has completed.
We then use window subclassing to insert this window as the window procedure for my own window:
Then we implement the OnFinalMessage handler for our window: