我们来了解一下MFC程序创建的流程, 一下代码在控制台程序中,模拟MFC的运行流程,每一个流程的内容是在控制台输出一些语句。
程序运行的结果如下:
类图结构:
上图便是 MFC 程序 的运行流程
MFC.h
#pragma once
#include<iostream>
using namespace std;
class CObject
{
public:
};
class CCmdTarget : public CObject
{
public:
};
class CWinThread : public CCmdTarget
{
public:
virtual bool InitInstance()
{
cout << "CWinThread:InitInstance \n";
return true;
}
virtual int Run()
{
cout << "CWinThread:Run \n";
return 1;
}
};
//先声音 CWnd类 因为在 CWinApp中需要用到,但是却没有 实际定义 CWnd这个类
class CWnd;
class CWinApp : public CWinThread
{
public:
CWinApp* m_pCurrentWinApp;
CWnd* m_pMainWnd;
public:
CWinApp::CWinApp()
{
m_pCurrentWinApp = this;
}
virtual bool InitInstance()
{
cout << "CWinApp:InitInstance \n";
return true;
}
virtual int Run()
{
cout << "CWinApp:Run \n";
return CWinThread::Run();
}
virtual bool InitApplication()
{
cout << "CWinApp:InitApplication \n";
return true;
}
};
class CDocument : public CCmdTarget
{
public:
};
class CWnd : public CCmdTarget
{
public:
virtual bool Create();
bool CreateEx();
virtual bool PreCreateWindow();
};
class CView : public CWnd
{
public:
};
class CFrameWnd : public CWnd
{
public:
bool Create();
virtual bool PreCreateWindow();
};
CWinApp* AfxGetApp();
MFC.cpp
#include "my.h"
extern CMyWinAPP theApp;
CWinApp* AfxGetApp()
{
return theApp.m_pCurrentWinApp;
}
bool CWnd::Create()
{
cout << "CWnd::Create \n";
return true;
}
bool CWnd::CreateEx()
{
cout << "CWnd::CreateEx \n";
//PreCreateWindow 是虚函数,所以调用哪个类的PreCreateWindow是根据 传入的指针来确定的
PreCreateWindow();
return true;
}
bool CWnd::PreCreateWindow()
{
cout << "CWnd::PreCreateWindow \n";
return true;
}
bool CFrameWnd::Create()
{
cout << "CFrameWnd::Create \n";
//由于CFrameWnd 并没有重写 CreateEx 所以 调用父类的 CreateEx函数
CreateEx();
return true;
}
bool CFrameWnd::PreCreateWindow()
{
cout << "CFrameWnd::PreCreateWindow \n";
return true;
}
my.h
#include<iostream>
#include"MFC.h"
class CMyWinAPP :public CWinApp
{
public:
bool InitInstance();
};
class MyFrameWnd:public CFrameWnd
{
public:
MyFrameWnd::MyFrameWnd()
{
cout << "MyFrameWnd::MyFrameWnd \n";
//MyFrameWnd 并没有重写Create 所以 调用了 父类的Create函数
Create();
}
};
my.cpp
#include"my.h"
CMyWinAPP theApp;
bool CMyWinAPP::InitInstance()
{
//让父类也初始化
CWinApp::InitInstance();
cout << "CMyWinAPP::InitInstance \n";
m_pMainWnd = new MyFrameWnd();
return true;
}
void main()
{
CWinApp *pApp = AfxGetApp();
//初始化运行环境等工作
pApp->InitApplication();
//对给个类对象进行初始化工作
pApp->InitInstance();
//程序开始运行
pApp->Run();
system("pause");
}