views:

531

answers:

3

Hi all,

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?

+3  A: 

afx_msg is just an empty macro, it's basically just there to denote that the method is an MFC message handler for readability purposes. Even with afx_msg there you still need to have an entry in the message map.

Gerald
Nice to know that, something I've wondered about for awhile. Maybe I just have too much time on my hands... ;)
Shane MacLaughlin
+9  A: 

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.

ChrisN
A: 

Some of the Windows message are already handled by MFC, so in these cases you can get away with adding just the method to your derived class.

For example the CWnd class (as do many other MFC classes) already maps a few Windows messages into it's message map (i.e. *ON_WM_DRAWITEM*, *ON_WM_MEASUREITEM*, *ON_WM_ENTERIDLE* etc, etc).

But any other message not already mapped by MFC will need to have both a class method and an entry in the message map for it to work.

jussij