MFC程序的初始化

    在MFC中,InitApplication负责程序的初始化,InitInstance负责实例的初始化,它们两个都是CWinApp类的虚函数。下面是一个控制台应用程序Frame2,具体代码如下。

//mfc.h

#define BOOL int
#define TRUE 1
#define FALSE 0

#include <iostream.h>

class CObject
{
public:
	CObject::CObject(){}
	CObject::~CObject(){}
};

class CCmdTarget:public CObject
{
public:
	CCmdTarget::CCmdTarget(){}
	CCmdTarget::~CCmdTarget(){}
};

class CWinThread:public CCmdTarget
{
public:
	CWinThread::CWinThread(){}
	CWinThread::~CWinThread(){}

	virtual BOOL InitInstance(){
		cout<<"CWinThread::InitInstance \n";
		return TRUE;
	}
	virtual int Run(){
		cout<<"CWinThread:: Run \n";
		return 1;
	}
};

class CWnd;

class CWinApp:public CWinThread
{
public:
	CWinApp* m_pCurrentWinApp;
	CWnd* m_pMainWnd;

public:
	CWinApp::CWinApp(){ m_pCurrentWinApp=this; }
	CWinApp::~CWinApp(){}

	virtual BOOL InitApplication(){
		cout<<"CWinApp::InitApplication \n";
		return TRUE;
	}
	virtual BOOL InitInstance(){
		cout<<"CWinApp::InitInstance \n";
		return TRUE;
	}
	virtual int Run()
	{
		cout<<"CWinApp::Run \n";
		return CWinThread::Run();
	}

};

class CDocument:public CCmdTarget
{
public:
	CDocument::CDocument(){}
	CDocument::~CDocument(){}
};

class CWnd:public CCmdTarget
{
public:
	CWnd::CWnd(){}
	CWnd::~CWnd(){}

	virtual BOOL Create();
	BOOL CreateEx();
	virtual BOOL PreCreateWindow();
};

class CFrameWnd:public CWnd{
public:
	CFrameWnd::CFrameWnd(){}
	CFrameWnd::~CFrameWnd(){}
	BOOL Create();
	virtual BOOL PreCreateWindow();
};

class CView:public CWnd
{
public:
	CView::CView(){}
	CView::~CView(){}
};

//global function
CWinApp* AfxGetApp();

//mfc.cpp

#include "my.h"

extern CMyWinApp theApp; //external global object

BOOL CWnd::Create()
{
	cout<<"CWnd::Create \n";
	return TRUE;
}

BOOL CWnd::CreateEx()
{
	cout<<"CWnd::CreaeteEX \n";
	PreCreateWindow();
	return TRUE;
}

BOOL CWnd::PreCreateWindow()
{
	cout<<"CWnd::PreCreateWindow \n";
	return TRUE;
}

BOOL CFrameWnd::Create()
{
	cout<<"CFrameWnd::Create \n";
	CreateEx();
	return TRUE;
}

BOOL CFrameWnd::PreCreateWindow()
{
	cout<<"CFrameWnd::PreCreateWindow \n";
	return TRUE;
}

CWinApp* AfxGetApp()
{
	return theApp.m_pCurrentWinApp;
}

//my.h

#include <iostream.h>
#include "mfc.h"

class CMyWinApp:public CWinApp
{
public:
	CMyWinApp::CMyWinApp(){}
	CMyWinApp::~CMyWinApp(){}
	virtual BOOL InitInstance();
};

class CMyFrameWnd:public CFrameWnd
{
public:
	CMyFrameWnd();
	~CMyFrameWnd(){}
};

//my.cpp

#include "my.h"

CMyWinApp theApp; //global object

BOOL CMyWinApp::InitInstance()
{
	cout<<"CMyWinApp::InitInstance \n";
	m_pMainWnd=new CMyFrameWnd;
	return TRUE;
}

CMyFrameWnd::CMyFrameWnd()
{
	cout<<"CMyFrameWnd::CMyFrameWnd \n";
	Create();
}

void main()
{
	CWinApp* pApp = AfxGetApp();

	pApp->InitApplication(); //初始化程序
	pApp->InitInstance(); //初始化实例
	pApp->Run();
}

效果如下:


图(1)MFC的初始化顺序

  解析:

    MFC的初始化顺序为:InitApplication()  ---》InitInstance()---》Create() ----》 CreateEx () ---》PreCreateWindow () ----》CWinApp::Run() ----》CWinThread::Run()


你可能感兴趣的:(C++,mfc,初始化,实例)