假设有一个Dialog:MyDialog,以动态创建一组按钮为例说明。
1。在MyDialog.h中加入声明:
protected:
CButton m_btnWork[5]; //生成5个按钮
2。在MyDialog.cpp头部加入:
#define IDC_BUTTON_WORK 2005
3。在MyDialog.cpp中需要动态生成按钮的地方加入:
CRect rect; //按钮的位置和大小
rect.left = 20;
rect.right = rect.left + 100;
rect.top = 20;
rect.bottom = rect.top + 20;
for(int i=0;i<5;i++){
//确保按钮不会重合
rect.top+=30;
rect.bottom+=30;
//动态创建按钮
m_btnWork[i].CreateEx(NULL,
_T("BUTTON"), //说明是生成BUTTON,根据生成的东西不同,要作相应的改动
NULL,
WS_CHILD,
rect,
this,
ID_MYBTN+i);//生成edit控件
//设置按钮的Caption
CString text;
text.Format("button%d",i);
SetDlgItemText(IDC_BUTTON_WORK+i,text);
//显示控件
m_btnWork[i].ShowWindow(SW_SHOW);
}
如果要加入消息映射,则要:
1。在MyDialog.h中加入:
afx_msg void OnMyButtonClicked();
2。在MyDialog.cpp中,
BEGIN_MESSAGE_MAP(CDynamicCreateDlg, CDialog)
和
END_MESSAGE_MAP()
之间加入:
ON_BN_CLICKED(IDC_BUTTON_WORK, OnMyButtonClicked)
3。在MyDialog.cpp中加入:
void CMyDialog::OnMyButtonClicked()
{
// TODO: Add your control notification handler code here
MessageBox("Hello");
}