控件的动态创建-MFC方式

来源:互联网 发布:硬盘播出系统 软件 编辑:程序博客网 时间:2024/05/16 04:56

动态创建控件

    private:        void DyCreateControl();        void UnDyCreateControl();

/// 动态创建控件的好处 : 可以批量操作,创建数量可以超过255const int g_iRow = 20;const int g_iCol = 20;const DWORD g_dwCtrlIdBegin = 2000;const DWORD g_dwCtrlIdEnd = g_dwCtrlIdBegin + g_iRow * g_iCol - 1;const int g_nWidth = 20;const int g_nHeight = 20;void CMainDlg::DyCreateControl() {    int i = 0;    int j = 0;    int x = 0;    int y = 0;        CButton* pBtn = NULL;    RECT rt;        for (i = 0; i < g_iRow; i++) {        for (j = 0; j < g_iCol; j++) {            pBtn = new CButton;            assert(NULL != pBtn);                        SetRect(                &rt,                 x + j * g_nWidth,                 y + i * g_nHeight,                 x + j * g_nWidth + g_nWidth,                 y + i * g_nHeight + g_nHeight);            pBtn->Create(TEXT(""),                 WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON,                 rt, this, g_dwCtrlIdBegin + i * g_iRow + j);        }    }}void CMainDlg::UnDyCreateControl() {    int i = 0;    int j = 0;    CButton* pBtn = NULL;        for (i = 0; i < g_iRow; i++) {        for (j = 0; j < g_iCol; j++) {            pBtn = (CButton*)GetDlgItem(g_dwCtrlIdBegin + i * g_iRow + j);            if (NULL != pBtn) {                delete pBtn;                pBtn = NULL;            }        }    }}void CMainDlg::OnDestroy() {    CDialog::OnDestroy();    UnDyCreateControl();}BOOL CMainDlg::OnInitDialog(){CDialog::OnInitDialog();        DyCreateControl();// Add "About..." menu item to system menu.// IDM_ABOUTBOX must be in the system command range.ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);ASSERT(IDM_ABOUTBOX < 0xF000);CMenu* pSysMenu = GetSystemMenu(FALSE);if (pSysMenu != NULL){CString strAboutMenu;strAboutMenu.LoadString(IDS_ABOUTBOX);if (!strAboutMenu.IsEmpty()){pSysMenu->AppendMenu(MF_SEPARATOR);pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);}}// Set the icon for this dialog.  The framework does this automatically//  when the application's main window is not a dialogSetIcon(m_hIcon, TRUE);// Set big iconSetIcon(m_hIcon, FALSE);// Set small icon// TODO: Add extra initialization herereturn TRUE;  // return TRUE  unless you set the focus to a control}

响应消息

    afx_msg void OnBtnDyCreate(UINT nID);//}}AFX_MSG

//}}AFX_MSG_MAP    ///< 必须放在 //}}AFX_MSG_MAP外面    ON_COMMAND_RANGE(2000, 2399, OnBtnDyCreate)END_MESSAGE_MAP()

void CMainDlg::OnBtnDyCreate(UINT nID) {    CString str;    CButton* pBtn = (CButton*)GetDlgItem(nID);    str.Format("%d", nID & 0xf);    pBtn->SetWindowText(str);}







0 0
原创粉丝点击