views:

68

answers:

1
+1  Q: 

Message map macros

When do you use ON_COMMAND and when do we use ON_MESSAGE. What are the differences between them.

+4  A: 

ON_COMMAND is specifically used to handle a command message (i.e. WM_COMMAND) like the click of a button/menu item/toolbar button.

ON_MESSAGE is more generic and can be used for any windows message. It is usually used for less frequently handled messages for which specific message map macros have not been provided. You can use ON_MESSAGE to handle ON_COMMAND messages as well but you will have to extract message information (i.e. command ID) yourself.

Example:

See here:

In the message map:

ON_MESSAGE( WM_COMMAND, OnMyCommand )

The handler:

LRESULT CMyWnd::OnMyCommand( WPARAM wParam, LPARAM lParam ) 
{
   // ... Handle message here
   int commandId = LOWORD(wParam);

   switch(commandId){
   case ID_HELLOCOMMAND:
       MessageBox(0, "Hello there!", "ID_HELLO_COMMAND", MB_OK);
       break;
   // ... other commands here
   }

   return 0L;
}

Disclaimer: Owing to MFC's message pump mechanism, you may have to do a bit more than what's shown above. The best man to ask: Jeff Prosise

Vulcan Eager
Can you give an example for this "You can use ON_MESSAGE to handle ON_COMMAND messages as well but you will have to extract message information yourself" explanation.
ckv
@ckv: I added an example.
Vulcan Eager