MFC之CWinApp和CFrameWnd

  • anotherapp.h
#include<afxwin.h>
class myapp:public CWinApp
{
    virtual BOOL InitInstance();
};

class mywnd:public CFrameWnd
{
public:
    mywnd();
//protected:
    //DECLARE_MESSAGE_MAP();
};
  • anotherapp.cpp
#include "anotherapp.h"
//myapp cpc;
BOOL myapp::InitInstance()
{
    this->m_pMainWnd=new mywnd();
    this->m_pMainWnd->ShowWindow(this->m_nCmdShow);
    this->m_pMainWnd->UpdateWindow();
    return TRUE;
};
/*BEGIN_MESSAGE_MAP(mywnd,CFrameWnd)
    ON_WM_PAINT()
END_MESSAGE_MAP()*/
mywnd::mywnd()
{
    this->Create(NULL,TEXT("喜欢小松鼠"));
}
  • duwa.cpp
#include "anotherapp.h"
myapp cpc;//调用写好的窗体类

输出结果:

  •  消息映射----我们已知微软利用C语言封装了很多winapi应用编程接口来满足窗体开发需要,但如果仅仅是继承cwinapp那么会有很多函数会被声明为虚函数,在运行自定义的窗口类时,这些继承关系会导致生成一个虚函数列表(可以参考一些C++实现多态的资料,子类重写父类虚函数实现多态的原理),造成性能方面的开销,因此,微软使用了消息映射
  • anotherapp.h
#include<afxwin.h>
class myapp:public CWinApp
{
    virtual BOOL InitInstance();
};

class mywnd:public CFrameWnd
{
public:
    mywnd();
protected:
    afx_msg void OnPaint();//固定语法,onpaint类
    DECLARE_MESSAGE_MAP();//固定语法---消息映射
};
  • anotherapp.cpp
#include "anotherapp.h"
//myapp cpc;
BOOL myapp::InitInstance()
{
    this->m_pMainWnd=new mywnd();
    this->m_pMainWnd->ShowWindow(this->m_nCmdShow);
    this->m_pMainWnd->UpdateWindow();
    return TRUE;
};
BEGIN_MESSAGE_MAP(mywnd,CFrameWnd)//消息映射函数
    ON_WM_PAINT()
END_MESSAGE_MAP()//消息映射函数
mywnd::mywnd()
{
    
    this->Create(NULL,TEXT("喜欢小松鼠"),WS_OVERLAPPEDWINDOW|WS_VSCROLL,CRect(100,100,380,300));
}

void mywnd::OnPaint()//实现的wm_paint消息映射函数
{
    CPaintDC cp(this);//设备上下文
    CRect rect;//窗体上空白的部分
    this->GetClientRect(&rect);
    cp.DrawText(TEXT("想和小松鼠一起看徐黑冬的MMA比赛"),-1,&rect,DT_SINGLELINE|DT_CENTER|DT_VCENTER);
}
  • 主函数调用
#include "anotherapp.h"
myapp cpc;

运行结果:

原文地址:https://www.cnblogs.com/saintdingspage/p/12117412.html