"Debug Assertion Failed" when MFC button control EnableWindow method is used in class constructor

2.3k views Asked by At

I am using Visual Studio 2019 and building a C++ desktop application. I have a dialog class inherited from CDialogEx. In this class I have a few buttons, i.e. CButton as members. When I use the EnableWindow method in the class constructor, it reports:

Debug Assertion Failed! Program C:\WINDOWS\SYSTEM32\mfc140ud.dll File: d....\winocc.cpp line 345

If I commented it out the application worked fine. Any idea why I have this error? All I wanted to do is to disable the buttons as soon as the dialog shows up - that is why I use this method in the constructor.

enter image description here

2

There are 2 answers

0
PaulMcKenzie On BEST ANSWER

There is a difference between a C++ class and the actual creation of the dialog window and its controls.

The constructor is for class related items, not window related items. For example, if you want to initialize member variables, then the constructor would be the place for it. But at construction, no dialog window has been created, thus there are no child controls that exist, thus the error you're seeing.

The place where you can assume that the window is created is in the dialog's OnInitDialog member function. This is where you should be able to call EnableWindow on the controls.

If you do not have an OnInitDialog, you can add that function using the class wizard.

0
Rubayat26 On

I got the same debug assertion failed with the same winocc.cpp error. The issue for me was that I was creating the mainframe constructor with no code in it. Once I added a simple create() inside it. The program compiled and the error did not show up again.

CMainFrame::CMainFrame()
{
    // TODO: add member initialization code here
    
    Create(NULL,(LPCTSTR)"User Input Controls",WS_OVERLAPPEDWINDOW,
        rectDefault,NULL, MAKEINTRESOURCE(IDR_MENU1));
}