0
votes

I am trying to create a button dynamically. I have read some other resource and make the following code:

BEGIN_MESSAGE_MAP(Cdynamic_button_sdiView, CView)
    // Standard printing commands
    ON_BN_CLICKED(MYBUTTONID, OnMyBN_Click)
END_MESSAGE_MAP()
void Cdynamic_button_sdiView::OnInitialUpdate()
{
    CView::OnInitialUpdate();
    m_Button.Create(_T("Rearrange"), WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON, CRect(0, 0, 128, 32), this, MYBUTTONID); // here will create a button
}

I can make a button successfully when I start the MFC application. The problem is that when I try to open a new document by clicking:
enter image description here
I get an error and my app crashed at m_Button.Create(_T("Rearrange"), WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON, CRect(0, 0, 128, 32), this, MYBUTTONID);
enter image description here

1
There are 3 buttons on that assertion dialog. One of them will give away loads of helpful information, including the pre-condition that your code failed to meet.IInspectable
Why don't you put a breakpoint in the line 673 of your C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\atlmfc\src\mfc\wincore.cpp file and follow the Call Stack? The message is pretty clear on what direction you should follow!sergiol
And although I have suspicions on what is wrong with your code, I will not tell you them, because I want you to debug it! Some years later, you will see the benefits.sergiol
@sergiol: That line of code is executed potentially many, many times. Placing a breakpoint there isn't exactly practical. Nor is it necessary. The debug assertion takes you to just the information you had hoped to get from the breakpoint.IInspectable
@IInspectable: sflee can limit the number of times by using conditional breakpoints or by reducing its code base to a minimum viable code.sergiol

1 Answers

0
votes

I solved the problem with the following code:

Cdynamic_button_sdiView::Cdynamic_button_sdiView()
{
    // TODO: add construction code here
    m_Button = NULL;
}

Cdynamic_button_sdiView::~Cdynamic_button_sdiView()
{
    if (m_Button != NULL)
        delete m_Button;
}
void Cdynamic_button_sdiView::OnInitialUpdate()
{
    CView::OnInitialUpdate();

    if (m_Button != NULL)
        delete m_Button;

    m_Button = new CButton;
    m_Button->Create(_T("Rearrange"), WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON, CRect(0, 0, 128, 32), this, MYBUTTONID); // here will create a button
}

May be the problem is I should not re-create the window inside the OnInitialUpdate()