CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 1 of 1
  1. #1
    Join Date
    Oct 2002
    Timisoara, Romania

    MFC Dialog: How to handle notifications for dynamically created controls?

    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.
    #define IDC_MY_BUTTON    1234
    Of course, the ID is used as argument to the Create() method. Suppose you do that in OnInitDialog():
    BOOL CSampleDialog::OnInitDialog()
      m_pMyButton->Create("Dyn Button", WS_CHILD|BS_PUSHBUTTON, CRect(100,100, 28, 100), this, IDC_MY_BUTTON);
      return TRUE;
    In this simplified case, CSampleDialog is a dialog class, that should have at least this declaration:
    class CSampleDialog : public CDialog
      CSampleDialog(CWnd* pParent = NULL);
      virtual void DoDataExchange(CDataExchange* pDX);
    You should add here a function that will be the handler of the event. Notice that different handlers could have different signatures.
    afx_msg void OnMyButtonClicked();
    You should also provide a body for this function:
    void CSampleDialog::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:
    BEGIN_MESSAGE_MAP(CSampleDialog, CDialog)
      ON_BN_CLICKED(IDC_MY_BUTTON, &CSampleDialog::OnMyButtonClicked)
    Last edited by cilu; January 16th, 2007 at 10:45 AM.
    Marius Bancila
    Home Page
    My CodeGuru articles

    I do not offer technical support via PM or e-mail. Please use vbBulletin codes.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Windows Mobile Development Center

Click Here to Expand Forum to Full Width

On-Demand Webinars (sponsored)

We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.