在MFC中还有另一种创建对话框的方法:
1 在内存中建立对话框资源模版DLGTEMPLATE结构体。2 使用InitModalIndirect API函数即可创建模式对话框,非模式对话框使用CreateDialog API函数创建。代码如下:
// 创建内存对话框资源模版类,H文件
#pragma once
#define DLG_TEMPLATE_BUFFER_MAX_LENGT 1024
class CDlgTemplate
{ public: CDlgTemplate(int nBufferLength=DLG_TEMPLATE_BUFFER_MAX_LENGT); ~CDlgTemplate();private:
WORD* m_pBuffer;public:
DLGTEMPLATE* CreateTemplate(DWORD dwStyle,CRect& rect,CString strCaption,DWORD dwStyleEx=0);};// CPP文件
CDlgTemplate::CDlgTemplate(int nBufferLength)
{ m_pBuffer=new WORD[nBufferLength]; if ((!m_pBuffer)||(DLG_TEMPLATE_BUFFER_MAX_LENGT>nBufferLength)) { exit(0); }}CDlgTemplate::~CDlgTemplate()
{ if (m_pBuffer) { delete m_pBuffer; m_pBuffer=NULL; }} DLGTEMPLATE* CDlgTemplate::CreateTemplate(DWORD dwStyle,CRect& rect, CString strCaption,DWORD dwStyleEx){ WORD* pTemp=m_pBuffer; DLGTEMPLATE* pDlgTemp=(DLGTEMPLATE*)pTemp;// 对话框模版
pDlgTemp->style = dwStyle; pDlgTemp->dwExtendedStyle = dwStyleEx; pDlgTemp->cdit = 0;pDlgTemp->cx=rect.Width();
pDlgTemp->cy=rect.Height(); pDlgTemp->x=(short)rect.left; pDlgTemp->y=(short)rect.top; pTemp=(WORD*)(pDlgTemp+1);// 菜单
*pTemp++=0;// class
*pTemp++=0;// caption
wcscpy((WCHAR*)pTemp,strCaption); pTemp += strCaption.GetLength()+1;// font
return pDlgTemp;
}// 例子
class CMyDlg: public CDialog{ public: CMyDlg(); ~CMyDlg();public:
BOOL CreateModeDlg(CString strCaption,CRect rect,BOOL bMode=TRUE,CWnd* pParent=NULL);private:
CDlgTemplate m_dlgTemp; CEdit m_ctrlEdit;private:
HICON m_hIcon; enum { IDICON=1 };virtual BOOL OnInitDialog();
virtual void OnOK(); virtual void DoDataExchange(CDataExchange* pDX);};CMyDlg::CMyDlg()
{ m_hIcon = AfxGetApp()->LoadStandardIcon(IDI_APPLICATION);}CMyDlg::~CMyDlg()
{}
void CMyDlg::DoDataExchange(CDataExchange* pDX)
{ }BOOL CMyDlg::CreateModeDlg(CString strCaption,CRect rect,BOOL bMode,CWnd* pParent)
{ BOOL bResult=FALSE; DLGTEMPLATE* pTemp = NULL;pTemp=m_dlgTemp.CreateTemplate(WS_POPUPWINDOW|DS_MODALFRAME|WS_CAPTION,rect,strCaption);
if (bMode) { bResult=InitModalIndirect(pTemp, pParent); } else { bResult=CreateIndirect(pTemp, pParent); }return bResult;
}BOOL CMyDlg::OnInitDialog()
{ CDialog::OnInitDialog();if (m_hIcon)
{ SetIcon(m_hIcon, TRUE); // 设置大图标 SetIcon(m_hIcon, FALSE); // 设置小图标 }// 创建编辑框
CRect rect(0,0,50,20); if (!m_ctrlEdit.Create(WS_CHILD|WS_VISIBLE|WS_BORDER,rect,this,2)) { return FALSE; }return TRUE;
}void CMyDlg::OnOK()
{ CDialog::OnOK();}
useage
模式CMyDlg dlg;CString result;dlg.CreateModeDlg(_T("123"),CRect(0,0,100,100),this);if (IDOK==dlg.DoModal()){}
非模式
CMyDlg dlg;CString result;if(dlg.CreateModeDlg(_T("123"),CRect(0,0,100,100),FALSE,this)){ dlg.ShowWindow(SW_SHOW);}