brent's hut

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

posted on 2008-11-19 15:10 brent 阅读(988) 评论(0)  编辑 收藏 引用 所属分类: C++Windows


只有注册用户登录后才能发表评论。
【推荐】超50万行VC++源码: 大型组态工控、电力仿真CAD与GIS源码库
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理