1. 对于Dialog程序
每个自己的MFC程序都有一个派生自CWinApp的类(CMyApp) 和 一个该类的全局对象 CMyApp theApp;
CMyApp -> CWinApp -> CWinThread -> CCmdTarget -> CObject
以下摘自 winmain.cpp
int AFXAPI AfxWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, _In_ LPTSTR lpCmdLine, int nCmdShow) { // ... CWinThread* pThread = AfxGetThread(); CWinApp* pApp = AfxGetApp(); // ... if (!pThread->InitInstance()) { if (pThread->m_pMainWnd != NULL) { TRACE(traceAppMsg, 0, "Warning: Destroying non-NULL m_pMainWnd/n"); pThread->m_pMainWnd->DestroyWindow(); } nReturnCode = pThread->ExitInstance(); goto InitFailure; } //... }
由上可见pThread->InitInstance()
CMyApp::InitInstance() 被调用
在这个函数中 窗口被
1. 创建
2. 显示
以下代码摘自CMyApp.cpp
BOOL CMyApp::InitInstance() { // ... CWinApp::InitInstance(); //... CMyDlg dlg; m_pMainWnd = &dlg; INT_PTR nResponse = dlg.DoModal(); if (nResponse == IDOK) { // TODO: Place code here to handle when the dialog is // dismissed with OK } else if (nResponse == IDCANCEL) { // TODO: Place code here to handle when the dialog is // dismissed with Cancel } }
其中CMYDlg dlg 在基类的构造函数中设置窗体的style
在DoModal中创建并显示窗体
在DoModal中进入消息循环
对于Modal window 在CWnd::RunModalLoop() 函数用来进行消息循环
不需要调用CWinApp::Run();
这样一个dialog的
创建
显示
消息循环
的过程就很清楚了
2. 对于文档程序 基本原理相同
以下代码摘自MyDoc.cpp
BOOL CMyDocApp::InitInstance() { // ... CWinAppEx::InitInstance(); // ... // The one and only window has been initialized, so show and update it m_pMainWnd->ShowWindow(SW_SHOW); m_pMainWnd->UpdateWindow(); // ... }
程序不会被中断
在CWinApp::Run中进行消息循环
以下摘自winmain.cpp
int AFXAPI AfxWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, _In_ LPTSTR lpCmdLine, int nCmdShow) { // Perform specific initializations if (!pThread->InitInstance()) { if (pThread->m_pMainWnd != NULL) { TRACE(traceAppMsg, 0, "Warning: Destroying non-NULL m_pMainWnd/n"); pThread->m_pMainWnd->DestroyWindow(); } nReturnCode = pThread->ExitInstance(); goto InitFailure; } nReturnCode = pThread->Run(); }