您的位置:首页 > 移动开发

mfc 封装 theapp winmain afxGetapp

2011-06-09 19:14 696 查看
解决疑惑:afxGetApp () 获得theApp 的指针的过程

基本上是这样的

一,定义

class ModuleState
{
public:
WinApp* m_pcurrentApp;
HINSTANCE m_hCurrentInst;

};

二,生成全局对象

ModuleState state;(这个对象应该比theapp 生成的早点。自己这样认为的,没做实验验证迟了的后果)

三 全局函数 GblGetModuleState (类似afxGetModuleState 或者 AfxGetApp. 自己写的么,就不使afx 了!)

ModuleState* GblGetModuleState()
{
return &state;
}

四, 在WinApp的构造函数中,初始化state的m_pcurrentApp

WinApp::WinApp()
{
GblGetModuleState()->m_pcurrentApp = this;
}

五,为了验证是否是自己的Myapp:public Winapp生成的 theapp

使用两个虚函数 winapp::Instance(){cout<<"in winapp";}

myapp::Instance(){cout<<"in myapp";}

int main()
{
WinApp* pApp = GblGetModuleState()->m_pcurrentApp ;
pApp->InitInstance ();
int c;
scanf("%d",&c); //完全是为了让程序停下来,看看输出的结果
return 0;
}

结论 : 1,mfc 程序中当然不可能只有一个 theapp 全局对象,我们关注的太紧密,自己就短视了。

2,这完全是自己做的一个 小实验。类似 mfc 的封装过程 。

附上实验代码 (本来相传附件的,没找到在哪操作。知道的给我说说)

//       module.h
//=====================================================
#ifndef  MODULE_STATE
#include "winapp.h"
class ModuleState
{
public:
WinApp*  m_pcurrentApp;
HINSTANCE m_hCurrentInst;
};
ModuleState* GblGetModuleState();

ModuleState  state;

ModuleState* GblGetModuleState()
{
return &state;
}
#define MODULE_STATE
#endif
//    winapp.h
//============================================
#ifndef  WINAPP
class WinApp
{
public:
HINSTANCE m_hInstance;
WinApp();

virtual bool InitInstance()
{
printf("in winapp");
return true;
}
};
#define  WINAPP
#endif
//       main.cpp
//===========================================
#include <windows.h>
#include <iostream>

#include "winapp.h"
#include "Modulestate.h"
WinApp::WinApp()
{
GblGetModuleState()->m_pcurrentApp = this;
}
class MyApp:public WinApp
{
int nCmdShow;
virtual bool InitInstance()
{
printf(" in  myapp  instance ");
return true;
}
};

MyApp theApp;

int main()
{
WinApp* pApp = GblGetModuleState()->m_pcurrentApp ;
pApp->InitInstance ();
int c;
scanf("%d",&c);
return 0;
}

//   vs2008    win32 console application
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: