1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Handling notifications for dynamically created control.

Discussion in 'MFC' started by d_arin100, Oct 7, 2009.

  1. d_arin100

    d_arin100 New Member

    Joined:
    Sep 25, 2009
    Messages:
    10
    Likes Received:
    3
    Trophy Points:
    0
    Location:
    Bangalore

    Introduction



    This article is about how we can create controls dynamically without using wizard and how to handle notification for dynamically created control. Here I will try to explain it by the notification BN_CLICKED for a button.

    Working



    Following three things we need to do for creating the button control dynamically.

    1. Need to define a button ID in the “resource.h” file and that should be given a unique integer value.
    Code:
       
    #define IDC_BUTTON1    4652
    
    2. Defining handler with correct signature. For this we need to add the button ID as argument to the Create() method. Suppose we are creating it in OnInitDialog().
    Code:
       
    BOOL CMyDialog::OnInitDialog()
    {
    	CDialog::OnInitDialog();
    	/// “m_wndPushButton” is a member variable of CButton class.
    	m_wndPushButton.Create (_T ("Push Button"), 
    		WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON, 
    		CRect(100, 100, 150, 150), 
    		this, IDC_BUTTON1);
    	return TRUE;   
    }
    
    Here the “CMyDialog” is a dialog class and its declaration looks like...
    Code:
       
    class CMyDialog: public CDialog   
    {     // Construction     
    public:        
    	CMyDialog (CWnd* pParent = NULL);     // standard constructor       
    protected:        
    	virtual void DoDataExchange(CDataExchange* pDX);         
    	DECLARE_MESSAGE_MAP()   
    };
    
    Now we need to add handler function declaration of the event within the class declaration.
    Code:
       
    afx_msg void OnButton1Clicked();
    
    And need to define the handler function in the corresponding source file (.cpp file).
    Code:
       
    void CMyDialog :: OnButton1Clicked()
    {
    /////////////
    }
    
    3. The last thing we need to add an entry to the message map of the class by specifying the ID of the control and the handler function of the notification.
    Code:
       
    BEGIN_MESSAGE_MAP(CMyDialog, CDialog)
    //{{AFX_MSG_MAP(CMyDialog)        
    ON_BN_CLICKED(IDC_BUTTON1, OnButton1Clicked)        
    //}}AFX_MSG_MAPEND_MESSAGE_MAP()
    
     
  2. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,293
    Likes Received:
    365
    Trophy Points:
    83
  3. rasd123

    rasd123 Banned

    Joined:
    Nov 4, 2009
    Messages:
    40
    Likes Received:
    0
    Trophy Points:
    0
    I like this's, cool!
     

Share This Page