I have some buttons and I want to write one message handler for all of them. Is there any way to find out which button is clicked? In C#, there was a parameter (sender), does MFC have something like that? Or do I have to write the same message handler for all of the buttons individually?
The best option is probably to give all the buttons consecutive ID numbers then use ON_COMMAND_RANGE(FIRST_BUTTON_ID, LAST_BUTTON_ID, HandlerFunction). Then HandlerFunction will take a UINT nID which will be the ID number of the button which called the handler. More info here
For typical WM_COMMAND messages, the lParam member of the message is supposed to hold the HWND of the sender--if the sender was a window. As @Redeye replied, you can put all your buttons in a range and write a ON_COMMAND_RANGE() entry in the message table and an OnCommand(UINT nCmd) (or whatever you name it) as a member function of your window, dialog, view, frame, or document class. The buttons don't necessarily have to be in a range. You could just put a single entry for each button ID as an ON_COMMAND_RANGE(IDC_BUTTON1, IDC_BUTTON1)--or whatever the identifier is. Thjust ere is no rule for that macro that the start and stop ranges have to be different.
You could write your own message cracking macro, that basically does what ON_COMMAND_RANGE() does, but just takes a single entry.
You could also call CWnd::GetCurrentMessage() in your handler and crack that in the handler to retrieve the command. The LOWORD of the wParam member of the message holds the control identifier. The lParam member of the message holds the sending controls HWND--if it was a window. For something like a toolbar, toolbar buttons are not real buttons but drawn by the toolbar such that the lParam will always be the HWND of the toolbar.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With