David Alfonso David Alfonso - 6 months ago 37
C++ Question

How to handle messages from dynamically created controls in an MFC app?

Imagine I have a CDialog which creates controls dynamically when the user clicks a button. It could be like this:

// We don't know which is the first id for the new buttons until runtime (!)
MyDialog::MyDialog(/*whatever parameters needed*/, first_id)
: next_id_(first_id)
{ /*...*/ }

BOOL MyDialog::OnSomeButtonClicked()
CButton* new_button = new CButton;
new_button->Create("Caption", WS_CHILD | WS_VISIBLE, this->new_button_rect_,
this, this->next_id_++);

Then my question would be: How could I handle messages from this button? Is it possible to use the MFC message map facility?

The solution should work in both vs6 and vs2005.

Thank you!


These are the solutions I've found so far in order of relevance:

  1. Use ON_COMMAND_RANGE if you can define the range of the control IDs you want to handle.

  2. Overload CWnd::PreTranslateMessage() and do whatever stuff you want with the messages received. NOTE: When dealing with buttons, take into account that the BN_CLICKED event is NOT sent to PreTranslateMessage but directly sent to the window procedure.

  3. Overload CWnd::WindowProc() and do whatever stuff you want with the messages received. NOTE that when dealing with buttons this is the ONLY WAY I've found to handle the BN_CLICKED event.

Interesting links:

I hope this helps... thank you all for your contributions.