AfxGetMainWnd[
^] does what the name suggests - it fetches the main window CWnd for the application.
So sending a WM_CLOSE message to that will always close the application, and both windows.
What you need to do is send WM_CLOSE to the second dialog - which means locating the CWnd instance for that. If you are using CDialog as the base class, it derives from CWnd, so you can get it directly from your constructed instance before you display it.