MFC 动态创建按钮
首先在对话框(模式对话框,无模式对话框)中添加一个ADD按钮,通过点击按钮产生的通告消息调用::OnBtnAdd()方法。此方法会在对话框的左上角创建一个按钮。
当然首先要在和次对话框相关联的类中添加一个按钮(CButton)的对象m_btn。
示例1:添加一个BOOL类型变量(m_bIsCreate)用来表示此按钮是否已经创建,初始化为FALSE。
1 void CTestDlg::OnBtnAdd()
2 {
3 // TODO: Add your control notification handler code here
4
5 if (m_bIsCreate == FALSE)
6 {
7 m_btn.Create("安妮", BS_DEFPUSHBUTTON | WS_VISIBLE | WS_CHILD,
8 CRect(0,0,100,100),this,123);
9 m_bIsCreate = TRUE;
10 }
11 else
12 {
13 m_btn.DestroyWindow();
14 m_bIsCreate = FALSE;
15 }
16 }
2 {
3 // TODO: Add your control notification handler code here
4
5 if (m_bIsCreate == FALSE)
6 {
7 m_btn.Create("安妮", BS_DEFPUSHBUTTON | WS_VISIBLE | WS_CHILD,
8 CRect(0,0,100,100),this,123);
9 m_bIsCreate = TRUE;
10 }
11 else
12 {
13 m_btn.DestroyWindow();
14 m_bIsCreate = FALSE;
15 }
16 }
示例2:通过静态变量(b_IsCreate)用来表示此按钮是否已经创建,初始化为FALSE。
1 void CTestDlg::OnBtnAdd()
2 {
3 // TODO: Add your control notification handler code here
4
5 static b_IsCreate = FALSE;
6 if (b_IsCreate == FALSE)
7 {
8 m_btn.Create("安妮", BS_DEFPUSHBUTTON | WS_VISIBLE | WS_CHILD,
9 CRect(0,0,100,100),this,123);
10 b_IsCreate = TRUE;
11 }
12 else
13 {
14 m_btn.DestroyWindow();
15 b_IsCreate = FALSE;
16 }
17
18 }
2 {
3 // TODO: Add your control notification handler code here
4
5 static b_IsCreate = FALSE;
6 if (b_IsCreate == FALSE)
7 {
8 m_btn.Create("安妮", BS_DEFPUSHBUTTON | WS_VISIBLE | WS_CHILD,
9 CRect(0,0,100,100),this,123);
10 b_IsCreate = TRUE;
11 }
12 else
13 {
14 m_btn.DestroyWindow();
15 b_IsCreate = FALSE;
16 }
17
18 }
示例3:从CWnd派生出的类,其内部都有一个成员变量m_hWnd保存了和窗口相关的句柄,当对象和窗口相关的时候,句柄就有值了。如果对象和窗口没有相关的时候,句柄是为空的。
1 void CTestDlg::OnBtnAdd()
2 {
3 // TODO: Add your control notification handler code here
4
5 if (!m_btn.m_hWnd)
6 {
7 m_btn.Create("安妮", BS_DEFPUSHBUTTON | WS_VISIBLE | WS_CHILD,
8 CRect(0,0,100,100),this,123);
9 }
10 else
11 {
12 m_btn.DestroyWindow();
13 }
14
15 }
2 {
3 // TODO: Add your control notification handler code here
4
5 if (!m_btn.m_hWnd)
6 {
7 m_btn.Create("安妮", BS_DEFPUSHBUTTON | WS_VISIBLE | WS_CHILD,
8 CRect(0,0,100,100),this,123);
9 }
10 else
11 {
12 m_btn.DestroyWindow();
13 }
14
15 }