+ Reply to Thread
Results 1 to 3 of 3

Thread: Create event handler for dynamically created conrtol in MFC.

  1. #1

    Create event handler for dynamically created conrtol in MFC.

    I have a MFC application.

    It takes input from user and creates that number of buttons dynamically.

    How can I created Event handler for those dynamically created buttons?

    Please help.

  2. #2
    Example:

    Code:
    #define BUTTON_RANGE_START	1000
    #define BUTTON_RANGE_END	1100
    
    class CMyDialog: public CDialog
    {
        afx_msg void OnButton(UINT nButtonID) ;
        std::vector<CButton *> vButtons ;
        void CreateButtonsDynamically(int nButtons) ;
        void DeleteButtons() ;
    }
    
    BEGIN_MESSAGE_MAP(CMyDialog, CDialog)
           ON_CONTROL_RANGE(BN_CLICKED, BUTTON_RANGE_START, BUTTON_RANGE_END, OnButton)
    END_MESSAGE_MAP()
    
    void CMyDialog::OnButton(UINT nButtonID)
    {
    }
    
    void CMyDialog::DeleteButtons()
    {
    	std::vector<CButton *>::iterator itr = vButtons.begin() ;
    
    	for (; itr != vButtons.end(); itr++)
    	{
    		delete *itr ;
    	}
    
    	vButtons.clear() ;
    }
    
    void CMyDialog::CreateButtonsDynamically(int nButtons)
    {
    	int nTop	= 10 ;
    	int bBottom = 30 ;
    	for (int nButtonIndex = 0; nButtonIndex < nButtons; nButtonIndex++)
    	{
    		CString strText ;
    		strText.Format("Button - %d", nButtonIndex) ;
    		CButton *pButton = new CButton() ;
    		pButton->Create(strText, WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON,
    						CRect(10, nTop, 80, bBottom), this, BUTTON_RANGE_START + nButtonIndex) ;
    		pButton->ShowWindow(TRUE) ;
    		pButton->UpdateWindow() ;
    		vButtons.push_back(pButton) ;
    		nTop	+= 20 ;
    		bBottom += 20 ; 
    	}
    }
    
    CreateButtonsDynamically(5) ;

  3. #3
    Great job and nice example.

+ Reply to Thread

Tags for this Thread

Bookmarks

Posting Permissions

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