MFC实现对话框与控件的自适应调节
一.对话框属性设置
先将对话框的Border属性由Dialog Frame设置为Resizing。
二.添加消息处理函数
类向导 -> 消息(WM-SIZE)添加处理函数->void COnshowDlg::OnSize(UINT nType, int cx, int cy)。
三.添加代码
在.h文件中声明:
void ResizeUI();
vector<CRect> m_vec_rect_;
源文件:
BOOL COnshowDlg::OnInitDialog()
{
CBCGPDialog::OnInitDialog();
//获取区域
CRect rect;
GetWindowRect(&rect);
m_vec_rect_.push_back(rect);
CWnd* pWnd = GetWindow(GW_CHILD);//获取子窗体
while(pWnd)
{
pWnd->GetWindowRect(rect);
m_vec_rect_.push_back(rect);
pWnd = pWnd->GetNextWindow();
}
}
void COnshowDlg::OnSize(UINT nType, int cx, int cy)
{
CBCGPDialog::OnSize(nType, cx, cy);
if(nType != SIZE_MINIMIZED)
{
ResizeUI();
}
}
void COnshowDlg::ResizeUI()
{
if (m_vec_rect_.size() > 0)
{
CRect rect;
GetWindowRect(&rect);
ScreenToClient(rect);
//第一个保存的是对话框的Rect
CRect saveRect = m_vec_rect_[0];
//根据当前和之前保存的对话框的宽高求比例
float x = rect.Width() * 1.0f / saveRect.Width();
float y = rect.Height() *1.0f/ saveRect.Height();
int iSize = m_vec_rect_.size();
int idx = 1;
ClientToScreen(rect);
CRect saveChild;
CWnd* pWnd = GetWindow(GW_CHILD);
while(pWnd && idx < iSize)
{
saveChild = m_vec_rect_[idx];
//根据比例调整控件上下左右距离对话框的距离
saveChild.left = rect.left + (saveChild.left - saveRect.left)*x;
saveChild.right = rect.right + (saveChild.right - saveRect.right)*x;
saveChild.top = rect.top + (saveChild.top - saveRect.top)*y;
saveChild.bottom = rect.bottom + (saveChild.bottom - saveRect.bottom)*y;
ScreenToClient(saveChild);
pWnd->MoveWindow(saveChild);
pWnd = pWnd->GetNextWindow();
++idx;
}
}
}
四.效果如下
原始:
最大化(全屏):