通常我们理解在窗口创建时发出消息WM_CREATE,但是在这个消息之前还有一个消息是被发出的WM_NCCREATE。
即:
WM_NCCREATE
WM_CREATE
对应的,在窗口被关闭时发出消息WM_DESTROY,WM_NCDESTROY。
顺序:
WM_DESTROY
WM_NCDESTROY
这里要注意的是,在一个窗口被关闭时,如果这个窗口存在子窗口,那么会先发送子窗口的WM_DESTROY和WM_NCDESTROY消息,接着发送父窗口的WM_DESTROY和WM_NCDESTROY消息。
顺序:
WM_DESTROY //CHILD,子窗口消息
WM_NCDESTROY //CHILD,子窗口消息
WM_DESTROY //Parent,父窗口消息
WM_NCDESTROY //Parent,父窗口消息
下面通过例子来验证这个执行顺序:
1.新建立一个MFC工程,工程名TestCreate,这时已经有一个默认的窗体TestCreate,设置如下:
2.接下来添加子窗体TestChild,不做设置。
3.添加打开子窗体事件响应:
- #include "TestChild.h"
- void CTestCreateDlg::OnButton2() //打开子窗体
- {
- if (!frm.GetSafeHwnd())
- {
- frm.Create(IDD_TESTCHILD_DIALOG,this);
- }
- frm.ShowWindow(SW_SHOW);
- }
4.为父窗体添加消息处理函数
- LRESULT CTestCreateDlg::DefWindowProc(UINT message, WPARAM wParam, LPARAM lParam)
- {
-
- switch(message)
- {
- case WM_CREATE:
- TRACE0("----------------------WM_CREATE/n");
- break;
- case WM_NCCREATE:
- TRACE0("----------------------WM_NCCREATE/n");
- break;
- case WM_DESTROY:
- TRACE0("----------------------WM_DESTROY/n");
- break;
- case WM_NCDESTROY:
- TRACE0("----------------------WM_NCDESTROY/n");
- break;
- default:
- break;
- }
- return CDialog::DefWindowProc(message, wParam, lParam);
- }
5.为子窗体添加消息处理函数
- LRESULT CTestChild::DefWindowProc(UINT message, WPARAM wParam, LPARAM lParam)
- {
-
- switch(message)
- {
- case WM_CREATE:
- TRACE0("----------------------WM_CREATE_CHILD/n");
- break;
- case WM_NCCREATE:
- TRACE0("----------------------WM_NCCREATE_CHILD/n");
- break;
- case WM_DESTROY:
- TRACE0("----------------------WM_DESTROY_CHILD/n");
- break;
- case WM_NCDESTROY:
- TRACE0("----------------------WM_NCDESTROY_CHILD/n");
- break;
- default:
- break;
- }
- return CDialog::DefWindowProc(message, wParam, lParam);
- }
到此,一个测试例程就做好了,Alt+2打开Output窗口,运行。
点击按钮打开子窗体,然后切换到父窗体,并点击关闭按钮,可以看到输出结果:
----------------------WM_NCCREATE
Loaded 'C:/WINDOWS/system32/version.dll', no matching symbolic information found.
Loaded 'C:/WINDOWS/system32/MSCTFIME.IME', no matching symbolic information found.
----------------------WM_CREATE
----------------------WM_NCCREATE_CHILD
----------------------WM_CREATE_CHILD
----------------------WM_DESTROY_CHILD
----------------------WM_NCDESTROY_CHILD
----------------------WM_DESTROY
----------------------WM_NCDESTROY