一、示例代码
msg.h
#include <afxwin.h>
class MyFrame : public CFrameWnd
{
public:
MyFrame();
DECLARE_MESSAGE_MAP()
afx_msg void OnLButtonDown(UINT, CPoint);
};
class MyApp : public CWinApp
{
public:
MyApp();
BOOL InitInstance();
};
msg.cpp
#include "msg.h"
MyApp myapp;
BEGIN_MESSAGE_MAP(MyFrame, CFrameWnd)
ON_WM_LBUTTONDOWN()
END_MESSAGE_MAP()
MyFrame::MyFrame()
{
this->Create(NULL, _T("I AM A WINDOW"));
}
void MyFrame::OnLButtonDown(UINT, CPoint)
{
MessageBox(_T("hello, mfc"));
}
BOOL MyApp::InitInstance()
{
MyFrame* frame = new MyFrame;
frame->ShowWindow(SW_SHOWNORMAL);
frame->UpdateWindow();
m_pMainWnd = frame;
return TRUE;
}
二、代码分析
这个小程序是为了说明Windows下的简单消息循环而写的代码,代码中InitInstance是MFC应用程序的入口函数;MyFrame 是窗口框架类,MyApp是应用程序类。一般的消息循环需要经过三个步骤:
1.声明消息映射
DECLARE_MESSAGE_MAP()
2.要处理的消息
BEGIN_MESSAGE_MAP(MyFrame, CFrameWnd)
ON_WM_LBUTTONDOWN()
END_MESSAGE_MAP()
3.消息函数的声明与实现
//头文件中
afx_msg void OnLButtonDown(UINT, CPoint);
//.cpp文件中
void MyFrame::OnLButtonDown(UINT, CPoint)
{
MessageBox(_T("hello, mfc"));
}