Dynamically creating a control in an MFC application

According to this link from Microsoft , it should be possible to define a CButton and specify its parent window (CDialog) without having CButton as a member of the dialog, but I couldn't do that.

So, if myButton is a member of a CDialog based class (myCDialog), the following code works:

BOOL myCDialog::OnInitDialog() {
  CDialog::OnInitDialog();
myButton.Create(_T("My button"), WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON, CRect(10, 20, 100, 50), this, 1000); 
...
}

      

But when I talk about dynamic creation, I want to be able to create as many buttons as I want dynamically (I can't define them as class members because I don't know how many!)

I tried the following code in another class with a pointer to myCDialog as the parent window, similar to the code shown in the link, but it fails:

CButton myButton;
myButton.Create(_T("My button"), WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON, CRect(10, 20, 100, 50), pmyCDialog, 1000);

      

So how can I create dynamic controls without defining them as a member of the CDialog class?

+3


source to share


1 answer


"(I can't define them as class members because I don't know how many!)"



You can make an array or vector CButton or CButton * as a class member. Assign a different ID to each of them when you call Create.

+1


source







All Articles