一、Win32Application Architecture
一个Win32 Application Architecture的代码结构如下:
LRESULT CALLBACK WinWordsProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam); //定义回调处理消息函数
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd){
// 创建一个窗口类分为三步:1.设计窗口类 2.注册窗口类 3.创建窗口 4.显示及更新窗口
// 步骤1.设计窗口类
WNDCLASS wc;
……
// 步骤2:注册窗口类
RegisterClass(&wc);
// 步骤3:创建窗口
HWND hw = NULL;
hw = CreateWindow("Icanth2011", "My Fist Win32 Application Project!~", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, 600, 400, NULL, NULL, hInstance, NULL);
// 步骤4:显示及更新窗口
ShowWindow(hw, SW_SHOWNORMAL);
UpdateWindow(hw);
// 消息循环
MSG msg;
BOOL bRet;
while((bRet=GetMessage(&msg, NULL, 0, 0))!=0){
if(-1 == bRet){
return -1;
}
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}
|
|
由此可见,Win32 Application 程序的组成分为如下几个部分:
1. 找到WinMain程序入口,并开始执行
2. 创建并设计窗口类
3. 注册窗口类
4. 创建窗口
5. 显示及更新窗口
6. 循环获取消息,经处理,交还系统让其调用相关回调消息处理函数进行处理。
二、MFCArchitecture
由于Windows API过多,不方便程序员使用,并且非面对象。于是MFC被用于对Windows API进行封装,MFC始终实际运行过程就是Win32 Application程序的运行过程。
1. MFC的项目结构
利用MFC AppWipzard自动生成的项目包括五个文件:CMyFirstMFCApp、CMainFrame、CFirstMFCDoc、CMyFirstCView、CAboutDlg。CMyFirstMFCApp继承自CWinApp,CMainFrame、CMyFirstCView、CAboutDlg都继承自CWnd,CFirstMFCDoc继承自CDocument,体现“文档/视图”结构。其项目结构如下所示:
2. MFC的执行过程
对于MFC框架运行过程进行剖析,最好的资料是MFC源代码,VC6位于“\Microsoft Visual Studio\VC98\MFC\SRC”下。执行过程如下:
定义theApp(:CMyFistMFCApp)
——>执行构造函数:CWinApp()->CMyFistMFCApp()->
——>程序入口_tWinMain (宏,定义为WInMain)
——>执行AftxWinMain
|
|
2.1 MFC的WinMain
在\SRC\APPMODUL.CPP中,可找到如下代码:
MFC\SRC\APPMODUL.CPP:
extern "C" int WINAPI
_tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPTSTR lpCmdLine, int nCmdShow)
{
// call shared/exported WinMain
return AfxWinMain(hInstance, hPrevInstance, lpCmdLine, nCmdShow);
}
|
|
而其中_tWinMain其实就是WinMain函数的宏,定义如下:
#define _tmain main
#define _tWinMain WinMain
#ifdef _POSIX_
#define _tenviron environ
|
|
由此可见,WinMain中调用AfxWinMain进行处理。MFC包含此文件,故将找到此入口并自动调用执行。
2.2 theApp全局对象
在Project\CMyFirstMFCApp.CPP中,可找到一行代码发下:
Project\CMyFirstMFCApp.CPP:
/
// The one and only CMyFistMFCApp object
CMyFistMFCApp theApp;
|
|
当定义theApp时,将先执行CWinApp(\MFC\SRC\APPCORE.CPP)的构造函数: