项目中遇到要动态创建单选按钮的情况,把代码整理如下: 对话框的成员变量: private: std::list<CButton*> m_radioList; //用来保存动态创建的按钮的指针,便于释放 对话框的成员函数: private: void ClearRadioList(); //释放动态创建的按钮 在对话框的OnInitDialog函数里添加创建按钮的代码: CRect rcBtn(20,0,120,15); //按钮高度为15,间隔高度为10 for (int i = 0; i < 5; i++) { DWORD dwStyle = WS_CHILD | WS_VISIBLE | BS_AUTORADIOBUTTON; rcBtn.top += 25; rcBtn.bottom += 25; CButton *pButton = new CButton(); if (0 == i) { dwStyle |= WS_GROUP; //第一个按钮时添加分组风格 } pButton->Create("单选按钮", dwStyle, rcBtn, this, 1000 + i); pButton->SetFont(GetFont()); //设置为父窗口的字体 m_radioList.push_back(pButton); } 添加按钮的响应: BOOL CCreateRadioDlg::OnCommand(WPARAM wParam, LPARAM lParam) { // TODO: Add your specialized code here and/or call the base class UINT nID,nMode; nID=LOWORD(wParam); nMode=HIWORD(wParam); if(nMode==BN_CLICKED) { if (nID < (1000 + m_radioList.size()) && nID >= 1000) { CString strTemp; strTemp.Format("%d",nID - 1000); MessageBox(strTemp); } } return CDialog::OnCommand(wParam, lParam); } void CCreateRadioDlg::ClearRadioList() { std::list<CButton*>::const_iterator it; for (it = m_radioList.begin(); it != m_radioList.end(); it++) { delete *it; } m_radioList.clear(); } void CCreateRadioDlg::OnDestroy() { CDialog::OnDestroy(); // TODO: Add your message handler code here ClearRadioList(); }