MFC 控件自适应对话框大小
转自:http://blog.csdn.net/chw1989/article/details/7488711
一。大小和位置都改变
1.首先为窗体类添加CRect m_rect,该成员变量用来记录窗体的当前大小。
2.在类向导里面(Ctrl+W),为窗体添加消息WM_SIZE的响应函数OnSize();
注意if(nType==1) return;这一句必须添加,否则最小化恢复的时候会出错。
1 void CPaperManagementDlg::OnSize(UINT nType, int cx, int cy) 2 { 3 CDialog::OnSize(nType, cx, cy); 4 if(nType==1) return;//最小化则什么都不做 5 // TODO: Add your message handler code here 6 CWnd *pWnd; 7 pWnd = GetDlgItem(IDC_STATIC); 8 ChangeSize(pWnd, cx, cy); 9 pWnd = GetDlgItem(IDC_FILE_TREE); 10 ChangeSize(pWnd, cx, cy); 11 pWnd = GetDlgItem(IDC_EDIT_NAME); 12 ChangeSize(pWnd, cx, cy); 13 pWnd = GetDlgItem(IDC_EDIT_REFERENCE); 14 ChangeSize(pWnd, cx, cy); 15 pWnd = GetDlgItem(IDC_EDIT_SUMMARY); 16 ChangeSize(pWnd, cx, cy); 17 pWnd = GetDlgItem(IDC_EDIT_REMARK); 18 ChangeSize(pWnd, cx, cy); 19 pWnd = GetDlgItem(IDC_BUTTON_UPDATE); 20 ChangeSize(pWnd, cx, cy); 21 pWnd = GetDlgItem(IDC_BUTTON_SAVE); 22 ChangeSize(pWnd, cx, cy); 23 pWnd = GetDlgItem(IDC_STATIC_1); 24 ChangeSize(pWnd, cx, cy); 25 pWnd = GetDlgItem(IDC_STATIC_2); 26 ChangeSize(pWnd, cx, cy); 27 pWnd = GetDlgItem(IDC_STATIC_3); 28 ChangeSize(pWnd, cx, cy); 29 pWnd = GetDlgItem(IDC_STATIC_4); 30 ChangeSize(pWnd, cx, cy); 31 GetClientRect(&m_rect);// 将变化后的对话框大小设为旧大小 32 }
其中函数ChangeSize是手动添加的用户函数,步骤如下
3.添加一个改变控件大小的用户函数,void ChangeSize(CWnd *pWnd, int cx, int cy),并编写代码
1 void CPaperManagementDlg::ChangeSize(CWnd *pWnd, int cx, int cy) 2 { 3 if(pWnd) //判断是否为空,因为对话框创建时会调用此函数,而当时控件还未创建 4 { 5 CRect rect; //获取控件变化前的大小 6 pWnd->GetWindowRect(&rect); 7 ScreenToClient(&rect);//将控件大小转换为在对话框中的区域坐标 8 9 // cx/m_rect.Width()为对话框在横向的变化比例 10 rect.left=rect.left*cx/m_rect.Width();//调整控件大小 11 rect.right=rect.right*cx/m_rect.Width(); 12 rect.top=rect.top*cy/m_rect.Height(); 13 rect.bottom=rect.bottom*cy/m_rect.Height(); 14 pWnd->MoveWindow(rect);//设置控件大小 15 } 16 }
真正改变控件大小的函数是ChangeSize函数,在OnSize中不断调用ChangeSize函数从而改变窗体中所有控件的大小。