Q: How can I handle notifications for dynamically created controls, such as BN_CLICKED for a button?
A: When you are creating controls dynamically (not by using a dialog template) you have to do the work the wizard does for you. It involves:
- defining a control ID (should be done in resource.h)
- defining a handler with the correct signature
- adding an entry to the message map of the class
When you define a button ID, make sure the ID is unique, otherwise you could get into problems.
Of course, the ID is used as argument to the Create() method. Suppose you do that in OnInitDialog():
#define IDC_MY_BUTTON 1234
In this simplified case, CSampleDialog is a dialog class, that should have at least this declaration:
m_pMyButton->Create("Dyn Button", WS_CHILD|BS_PUSHBUTTON, CRect(100,100, 28, 100), this, IDC_MY_BUTTON);
You should add here a function that will be the handler of the event. Notice that different handlers could have different signatures.
class CSampleDialog : public CDialog
CSampleDialog(CWnd* pParent = NULL);
virtual void DoDataExchange(CDataExchange* pDX);
You should also provide a body for this function:
afx_msg void OnMyButtonClicked();
The whole trick of ensuring the handler is called when the notification arrives is adding an entry to the message map of the CSampleDialog class, specifying the ID of the control and the function to handle the notification: