Resolving assertions pointing at ::IsWindow
22 January, 2009 § Leave a comment
In MFC, every control on a form is a window in itself. If the control is created dynamically, then usually you will find a call to the specific control’s Create method inside of an InitDialog or OnInitialUpdate for Dialogs or Views, respectively. Since the control is created dynamically, there exists a time that the control referenced before the Create method is called.
One example is when your dialog/view handles a Windows message that accesses the control. The message can be received before the control has been created, causing a debug assertion to fail. To fix this, make sure to call ::IsWindow before you modify the control. Before Create is called, the control is not a Window, but after Create is called it is. Tada!
Here is how your code should change (I am using GetDlgItem here for simplicity of the code example, otherwise I would prefer to use Dialog Data Exchange):
Before:
CProgressCtrl* wndProgressCtrl = (CProgressCtrl*) GetDlgItem( IDC_PROGRESS_BAR ); wndProgressCtrl->SetPos( 50 );
After:
CProgressCtrl* wndProgressCtrl = (CProgressCtrl*) GetDlgItem( IDC_PROGRESS_BAR ); if( ::IsWindow( wndProgressCtrl ) ) { wndProgressCtrl->SetPos( 50 ); }
Leave a Reply