应该注意:控件也是一个窗口。在添加控件的时候空间变量最好是全部变量或者是局部指针变量,这样即使函数结束也不会造成变量被销毁。下面以动态添加按钮为例的代码: CButton *pButton = new CButton; //一定要New CButton,否则程序会运行出错 pButton->Create("New Button", WS_CHILD|BS_DEFPUSHBUTTON, CRect(0, 0, 100, 50), this, 123); pButton->ShowWindow(SW_SHOW); 或者是如下代码: CButton *pButton = new CButton; //一定要New CButton,否则程序会运行出错 pButton->Create("New Button", WS_CHILD|BS_DEFPUSHBUTTON|WS_VISIBLE, CRect(0, 0, 100, 50), this, 123); 根据MFC的消息映射机制,应该更改三处代码。 (1)在头文件中修改代码 在protected的注释宏中间添加函数声明: protected: //{{AFX_MSG(CDemoMDIView) afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); afx_msg void OnNewButton(void); //}}AFX_MSG (2)在cpp文件中添加消息声明 BEGIN_MESSAGE_MAP(CDemoMDIView, CView) //{{AFX_MSG_MAP(CDemoMDIView) ON_WM_CREATE() //}}AFX_MSG_MAP // Standard printing commands ON_COMMAND(ID_FILE_PRINT, CView::OnFilePrint) ON_COMMAND(ID_FILE_PRINT_DIRECT, CView::OnFilePrint) ON_COMMAND(ID_FILE_PRINT_PREVIEW, CView::OnFilePrintPreview) //参数依次为控件ID、响应函数名称 ON_BN_CLICKED(123, OnNewButton) END_MESSAGE_MAP() (3)在cpp文件中添加函数代码 void CDemoMDIView::OnNewButton(void) { MessageBox("This is a new button!/nThis Function Handler was added manually!"); }