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:
- http://msdn.microsoft.com/en-us/library/k35k2bfs(VS.80).aspx
- http://msdn.microsoft.com/en-us/library/ms647591(VS.85).aspx
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
2010-08-10 06:28:25
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
2010-08-10 06:31:43
@ckv: I added an example.
Vulcan Eager
2010-08-26 15:44:30