探究MFC之Dialog窗口最大化时控件自适应
MFC的Dialog程序,在窗口最大化时,如何所有让子窗口(控件)按比例放大?
- 启动VisualC++6.0,New->MFC AppWizard(exe) 创建Dialog示例程序MFC02;
在ResourceView->Dialog属性对话框,选择开启最大化和最小化
在对话框初始化函数中,保存窗口初始大小。
///////////////////////////////////////////////////////////////////////////// // CMFC02Dlg message handlers BOOL CMFC02Dlg::OnInitDialog() { CDialog::OnInitDialog(); ... // TODO: Add extra initialization here //保存窗口初始大小 CRect rect; GetClientRect(&rect); m_nOldCx = rect.Width(); m_nOldCy = rect.Height(); //初始化完毕flag m_IsInitialized = TRUE; return TRUE; // return TRUE unless you set the focus to a control }
添加WM_SIZE的消息映射函数,当窗口大小变化后,调整窗口上的子窗口(控件)大小。
//WM_SIZE消息函数 void CMFC02Dlg::OnSize(UINT nType, int cx, int cy) { CDialog::OnSize(nType, cx, cy); // TODO: Add your message handler code here //对话框初始化后,窗口最大化和窗口复原时, //调用Readjust函数调整对话框上面控件的大小和位置 if (m_IsInitialized && (nType==SIZE_RESTORED || nType==SIZE_MAXIMIZED)) { Readjust(cx, cy); m_nOldCx = cx; m_nOldCy = cy; } } //根据窗口大小,调整子窗口(控件)大小 VOID CMFC02Dlg::Readjust(int cx, int cy) { //计算窗口比率 float fspx = (float)cx / m_nOldCx; float fspy = (float)cy / m_nOldCy; CRect rect; //获取子窗口(控件) CWnd * pWnd = this->GetWindow(GW_CHILD); while(pWnd != NULL) { pWnd->GetWindowRect(&rect); this->ScreenToClient(&rect); //重新计算控件位置和大小 int nNewx = (int)rect.left * fspx; int nNewy = (int)rect.top * fspy; int nNewWidth = (int)(rect.Width()* fspx); int nNewHeight = (int)(rect.Height() * fspy); //调整控件 pWnd->MoveWindow(nNewx, nNewy, nNewWidth, nNewHeight); //获取下一个子窗口(控件) pWnd = pWnd->GetWindow(GW_HWNDNEXT); } }
效果展示