我们需要根据程序输入或运行时信息在界面上动态生成一个或多个按钮,并分别添加消息响应,实现这一目标包括如下几步:
1.在类中声明按钮变量指针CButton btnArray[n];
2.在类中声明并定义按钮控件的ID, buttonID = 10000;
3.想要创建按钮的数量static const int n = 6;
主要这几行:
afx_msg void OnButtonClick(UINT uID);
static const int n = 6;
CButton btnArray[n];
static const int buttonID = 10000;
void AutoCreateButton(int n);
【.h文件】
class CMFCApplication2Dlg : public CDialogEx { protected: HICON m_hIcon; // 生成的消息映射函数 virtual BOOL OnInitDialog(); afx_msg void OnSysCommand(UINT nID, LPARAM lParam); afx_msg void OnPaint(); afx_msg HCURSOR OnQueryDragIcon(); afx_msg void OnButtonClick(UINT uID); DECLARE_MESSAGE_MAP() public: static const int n = 6; CButton btnArray[n]; static const int buttonID = 10000; void AutoCreateButton(int n); };
【cpp文件】
1、ON_COMMAND_RANGE(buttonID, buttonID + n - 1, OnButtonClick),注意些的位置
BEGIN_MESSAGE_MAP(CMFCApplication2Dlg, CDialogEx) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_BN_CLICKED(IDC_BUTTON1, &CMFCApplication2Dlg::OnBnClickedButton1) ON_COMMAND_RANGE(buttonID, buttonID + n - 1, OnButtonClick) END_MESSAGE_MAP()
2、AutoCreateButton(n); 写在OnInitDialog()函数里
BOOL CMFCApplication2Dlg::OnInitDialog() { CDialogEx::OnInitDialog(); ------省略 AutoCreateButton(n);//自动生成n个按钮 return TRUE; // 除非将焦点设置到控件,否则返回 TRUE }
3、OnButtonClick(UINT uID)
void CMFCApplication2Dlg::OnButtonClick(UINT uID) { //int nBtnID = uID - buttonID; }
4、AutoCreateButton(int n)的实现,一行最多5个按钮,大于5个显示在第二行
void CMFCApplication2Dlg::AutoCreateButton(int n) { DWORD dwStyle = WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON; int x1 = 20, y1 = 20, buttonSize = 100; int maxButtonsPerRow = 5; int buttonSpacing = 10; int verticalSpacing = 30;//第一行和第二行按钮的间距 for (int i = 0; i < n; i++) { CString str; str.Format(_T("Button %d"), i + 1); int row = i / maxButtonsPerRow; int col = i % maxButtonsPerRow; int x = 20 + col * (buttonSize + buttonSpacing); int y = 20 + row * (buttonSize + buttonSpacing) + row * verticalSpacing; btnArray[i].Create(str, dwStyle, CRect(x, y, x + buttonSize, y + buttonSize), this, buttonID + i); btnArray[i].SetFont(GetFont()); // 设置按钮控件字体 btnArray[i].ShowWindow(TRUE);
//这两行可以去掉,我是用来在按钮上显示图片的IDB_BITMAP1是图片的ID HBITMAP hBmpMLT = ::LoadBitmap(AfxGetInstanceHandle(), MAKEINTRESOURCE(IDB_BITMAP1)); btnArray[i].SetBitmap(hBmpMLT); y1 += 50; // 调整下一个按钮控件的位置 } }
我参考的博客:
MFC中动态创建多个按钮并实现其消息响应 - happyboy2 - 博客园 (cnblogs.com)