2016-09-30 90 views
0

我正在嘗試動態創建一個按鈕。我看過一些其他資源,使下面的代碼:
MFC SDI動態創建按鈕

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 
} 

我可以做一個按鈕成功當我開始MFC應用程序。問題是,當我嘗試通過單擊打開一個新的文檔:
enter image description here
我得到一個錯誤,我的應用程序在m_Button.Create(_T("Rearrange"), WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON, CRect(0, 0, 128, 32), this, MYBUTTONID);
enter image description here

+0

上有這種說法3個按鈕裏面的窗對話。其中一個會泄露大量有用的信息,包括代碼未能滿足的先決條件。 – IInspectable

+0

爲什麼不在C:\ Program Files(x86)\ Microsoft Visual Studio 12.0 \ VC \ atlmfc \ src \ mfc \ wincore.cpp'文件的第673行中放置斷點並遵循Call Stack?這個信息非常清楚你應該遵循什麼方向! – sergiol

+0

雖然我懷疑你的代碼有什麼問題,但我不會告訴你,因爲我希望你能對它進行調試!幾年後,你會看到好處。 – sergiol

回答

0

墜毀我解決了用下面的代碼的問題:

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 
} 

可能是問題是我不應該重新創建的OnInitialUpdate()