Re: MFC: adding a control into a dialog window



David Wilkinson wrote:
Man-wai Chang ToDie (33.6k) wrote:

void ChelloDlg::OnBnClickedEnable() {
CWnd *parentWnd = GetDlgItem(IDD_HELLO_DIALOG);
CStatic * newlabel = new CStatic();
newlabel->Create(_T("Hello World"), WS_CHILD | WS_VISIBLE,
CRect(10, 10, 100, 100), parentWnd);
}

I am using a button ID_ENABLE to trigger the adding of label into IDD_HELLO_DIALOG. The program would crash ("Debug Assertion Failed") when I hit the button.

What am I missing?

Man-wai:

The big thing you are missing is telling us what the dialog assertion says. "Crash" is never a meaningful description of a problem.

But I would imagine that the problem is that your parentwnd is NULL. GetDlgItem() will get the CWnd* of a child control of the dialog, and there is not one with the ID IDD_HELLO_DIALOG. Just pass the "this" pointer as the parent.

But a much easier way to do this kind of thing is to put the static control on the template and show/hide it as needed.


That would also prevent newlabel from going out of scope :-0
.