Hello MFC - The Message Map
The message map is MFC's way of avoiding the lengthy vtables that would be required
if every class had a virtual function for every possible message it might receive.
Any class derived from CCmdTarget can contain a message map.
- Declare the message map by adding a DECLARE_MESSAGE_MAP statement to the class declaration.
- Implement the message map by placing macros identifying the messages that the class will handle
between calls to BEGIN_MESSAGE_MAP and END_MESSAGE_MAP. - Add member functions to handle the messages.
- declare
DECLARE_MESSAGE_MAP()
- impl
BEGIN_MESSAGE_MAP(CMyApp, CWinApp)
ON_COMMAND(ID_HELP, &CWinApp::OnHelp)
END_MESSAGE_MAP()
begin message map
BEGIN_MESSAGE_MAP( theClass, baseClass )
Parameters:
- theClass
Specifies the name of the class whose message map this is.
- baseClass
Specifies the name of the base class of theClass.
Modify CMyApp
MyApp.cpp
- OnHelp()
#include "stdafx.h"
Copy stdafx.h and targetver.h to the project directory.
afxwin
MyApp.h
Use
#ifndef __AFXWIN_H__
#error "include 'stdafx.h' before including this file for PCH"
#endif
instead of
#include <afxwin.h>
Example
- MyApp.h
#pragma once
#ifndef __AFXWIN_H__
#error "include 'stdafx.h' before including this file for PCH"
#endif
class CMyApp :
public CWinApp
{
public:
CMyApp();
// Overrides
public:
virtual BOOL InitInstance();
// Implementation
DECLARE_MESSAGE_MAP()
};
- MyApp.cpp
#include "stdafx.h"
#include "MyApp.h"
#include "MainWindow.h"
BEGIN_MESSAGE_MAP(CMyApp, CWinApp)
ON_COMMAND(ID_HELP, &CWinApp::OnHelp)
END_MESSAGE_MAP()
CMyApp::CMyApp()
{
}
BOOL CMyApp::InitInstance()
{
m_pMainWnd = new CMainWindow();
m_pMainWnd->ShowWindow(SW_SHOW);
m_pMainWnd->UpdateWindow();
return TRUE;
}
CMyApp myApp;
浙公网安备 33010602011771号