CWinApp和CFrameWnd是MFC中两个重要的类, 其中CFrame代表窗体框架,可以调用Create函数创建窗口,CWinApp是控制整个应用程序的,要运行程序就必须将该类实例化,实例化会自动调用构造函数并调用InitInstance()这个函数。
MFC使用一种消息映射机制来处理消息,在应用程序框架中的表现就是一个消息与消息处理函数一一对应的消息映射表,以及消息处理函数的声明和实现等代码。当窗口接收到消息时,会到消息映射表中查找该消息对应的消息处理函数,然后由消息处理函数进行相应的处理。
hello.h
#include <afxwin.h>
class CMyApp : public CWinApp
{
public:
virtual BOOL InitInstance();//实例化类
};
class CMainWindow : public CFrameWnd
{
public:
CMainWindow();//窗口构造函数
protected:
afx_msg void OnPaint();//消息映射对应的处理函数
afx_msg void OnLButtonDown(UINT nFlags, CPoint point);//消息映射对应的处理函数
DECLARE_MESSAGE_MAP();//声明消息映射
};
hello.cpp
#include "hello.h"
CMyApp myApp;
BOOL CMyApp::InitInstance()
{
this->m_pMainWnd = new CMainWindow();
this->m_pMainWnd->ShowWindow(this->m_nCmdShow);
this->m_pMainWnd->UpdateWindow();
return true;
}
BEGIN_MESSAGE_MAP(CMainWindow, CFrameWnd)
ON_WM_PAINT() //映射到hello.h中的OnPaint函数,名字必须一样,否则报错
ON_WM_LBUTTONDOWN() //映射到hello.h中的OnLButtonDown函数
END_MESSAGE_MAP()
CMainWindow::CMainWindow()
{
this->Create(NULL, TEXT("THE HELLO APPLICATION"),
WS_OVERLAPPEDWINDOW | WS_VSCROLL,
CRect(100, 100, 380, 300));//创建窗口,窗口名为"THE HELLO APPLICATION", 带有滚动条, 窗口左上角在屏幕上坐标(100, 100), 右下角坐标(380, 300)
}
void CMainWindow::OnPaint()//处理绘制消息,Paint消息
{
CPaintDC dc(this); //DC对象 设备上下文 显示器 打印机等等
//dc.Ellipse(100, 100, 200, 300);//画椭圆
CRect rect;
this->GetClientRect(&rect);//获得客户区区域用来画字
dc.DrawText(TEXT("HELLO, MFC!"), -1, &rect, DT_SINGLELINE | DT_CENTER | DT_VCENTER);
}
转载于:https://my.oschina.net/u/2480857/blog/637942