首页 MFC动态创建对话框

MFC动态创建对话框

小白鼠 2019-05-12 02:32:33 0 3548

大概思路:新增一个类,作为对话框模板

DlgTemplate.h

#pragma once
 
#include "afx.h"
 
#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);
};

DlgTemplate.cpp

#include "DlgTemplate.h"
 
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;
}

自己的对话框

myDlg.h

#pragma once
#include <afxdialogex.h>
#include "DlgTemplate.h"
 
class myDlg : public CDialog
{
public:
	myDlg();
	~myDlg();
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);
};

myDlg.cpp

#include "myDlg.h"
#include "commonlog.h"
#include "DlgTemplate.h"
 
 
myDlg::myDlg()
{
	m_hIcon = AfxGetApp()->LoadStandardIcon(IDI_APPLICATION);
}
myDlg::~myDlg()
{
}
void myDlg::DoDataExchange(CDataExchange* pDX)
{
}
 
BOOL myDlg::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 myDlg::OnInitDialog()
{
	CDialog::OnInitDialog();
	if (m_hIcon)
	{
		SetIcon(m_hIcon, TRUE);   // 设置大图标
		SetIcon(m_hIcon, FALSE);  // 设置小图标
	}
 
	return TRUE;
}
 
 
void myDlg::OnOK()
{
	CDialog::OnOK();
}

调用模态对话框:

	myDlg am;
 
	am.CreateModeDlg(_T("ttt"), CRect(0, 0, 100, 100), TRUE, this);
 
	am.DoModal();

DoModal()有返回值,可以处理一下

对用非模态对话框

就是bMode改为false

显示就是am.ShowWindow(SW_SHOW);

那么如何在对话框中动态创建控件呢,见下一篇帖子

//控件风格 见帖子 MFC窗口以及控件风格 http://www.vmould.cn/?post=186



发表评论