我正在尝试动态创建一个按钮。我已阅读其他一些资源并制作以下代码:
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应用程序时,我可以成功创建一个按钮。问题是当我尝试通过点击打开新文档时:
我收到错误,我的应用程序在m_Button.Create(_T("Rearrange"), WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON, CRect(0, 0, 128, 32), this, MYBUTTONID);
时崩溃了
答案 0 :(得分: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()里面重新创建窗口