create mfc dialog by template will drive you mad.

create mfc dialog by template will drive you mad.

I have a dialog template in resource, and i have a dialog class, called CMyDialog.

And now, sometimes , i need CMyDialog to be a model dialog (WS_POPUP), sometimes be a child of another dialog(WS_CHILD).

How to make this done without duplicating the template in resource?

Call ModifyStyle after creation? Failed
Modify the LPCREATESTRUCT's style in CMyDialog::OnCreate ? Failed.
Override PreCreateWindow? Failed.

After a lot of tracing and a lot of googling. I worked out something like this:

BOOL CMyDialog::CreateAsChild(CWnd  *  pParent)
{
    
if ( ! IsWindow(pParent -> GetSafeHwnd()))
        
return  FALSE;

    m_lpszTemplateName 
=  ATL_MAKEINTRESOURCE(IDD_WALLLAYER_PROPERTYPAGE);   //  used for help
     if  (m_nIDHelp  ==   0 )
        m_nIDHelp 
=  LOWORD((DWORD_PTR)m_lpszTemplateName);

    HINSTANCE hInst 
=  AfxFindResourceHandle(m_lpszTemplateName, RT_DIALOG);
    HRSRC hResource 
=  ::FindResource(hInst, m_lpszTemplateName, RT_DIALOG);
    HGLOBAL hTemplate 
=  LoadResource(hInst, hResource);
    LPCDLGTEMPLATE lpDialogTemplate 
=  (LPCDLGTEMPLATE)LockResource(hTemplate);
    DLGTEMPLATEEX
*  lpDlgTmpEx  =  (DLGTEMPLATEEX *  )lpDialogTemplate;
    DWORD dwOldStyle 
=   0 ;
    BOOL bIsDlgEx 
=  lpDlgTmpEx -> signature  ==   0xFFFF ;
    
if (bIsDlgEx)
    {
        dwOldStyle 
=  lpDlgTmpEx -> style;
        lpDlgTmpEx
-> style  =  DS_SETFONT  |  WS_CHILD;
    }
    
else
    {
        dwOldStyle 
=  ((LPDLGTEMPLATE)lpDialogTemplate) -> style;
        ((LPDLGTEMPLATE)lpDialogTemplate)
-> style  =  DS_SETFONT  |  WS_CHILD;
    }
    m_lpDialogInit 
=  NULL;
    BOOL bResult 
=  CreateDlgIndirect(lpDialogTemplate, pParent, hInst);
    
if (bIsDlgEx)
        lpDlgTmpEx
-> style  =  dwOldStyle;
    
else
        ((LPDLGTEMPLATE)lpDialogTemplate)
-> style  =  dwOldStyle;
    UnlockResource(hTemplate);
    FreeResource(hTemplate);
    
return  bResult;
}

If you need your dialog to behavior as WS_POPUP or WS_CHILD without duplicating your dialog template, you just get an ugly answer. And anyone who know another better way, let me know please.

MFC

你可能感兴趣的:(create mfc dialog by template will drive you mad.)