c++visual-studio-2013mfccdialog

Create a control dynamically 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 the CButton as a member of the Dialog, but I couldn't do it.

So if myButton is a member of a CDialog-derived (myCDialog) class, 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 have 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?


Solution

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

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