Trapping messages in MFC - Whats the difference?
c++, message, mfc, windows
Solution
Both parts are necessary to add a message handler to a class. The message map should be declared inside your class, together with declarations for any message handler functions (e.g, `OnSize`).
class CClassWnd : public CBaseClassWnd {
...
afx_msg void OnSize(UINT nType, int cx, int cy);
DECLARE_MESSAGE_MAP
};
`afx_msg` is just an empty placeholder macro - it doesn't actually do anything, but is always included by convention.
The message map is then defined in the class's .cpp file:
BEGIN_MESSAGE_MAP(CClassWnd, CBaseClassWnd)
ON_WM_SIZE()
END_MESSAGE_MAP()
These macros generate a lookup table for the class which allows messages received by the window to be dispatched to the corresponding handler functions. The `ON_WM_SIZE` macro allows the `wParam` and `lParam` message parameters in the `WM_SIZE` message to be decoded into more meaningful values for the message handler function (`nType`, `cx`, and `cy` in this case). MFC provides macros for most window messages (`WM_LBUTTONDOWN`, `WM_DESTROY`, etc).
You can find more information on how message maps work in MFC here on MSDN.
Problem
I was just wondering what (if any) the difference was between the following two message traps in MFC for the function, OnSize(..). 1 - Via Message map: ``` BEGIN_MESSAGE_MAP(CClassWnd, CBaseClassWnd) ... ON_WM_SIZE() .. END_MESSAGE_MAP() ``` 2 - Via afx_message: ``` afx_msg type OnSize(...); ``` They seem to be used interchangeably, which one should be used or does it depend on other factors?