VC++之根据对话框大小调整控件大小
1、在对话框类中加入成员变量CRect m_rect;用于保存对话框大小变化前的大小;
2、在对话框的OnInitDialog()函数中获取对话框创建时的大小:GetClientRect(&m_rect);
3、在WM_SIZE的响应函数OnSize()中加入以下代码:
1:private:
CRect m_rect;
2:GetClientRect(&m_rect);
3:
void CButtonDlg::modify(CWnd* pWnd,int cx,int cy)
{
if (pWnd)
{
CRect rect; //获取控件变化前大小
pWnd->GetWindowRect(&rect);
ScreenToClient(&rect); //将控件大小转换为在对话框中得区域坐标
//cx/m_rect.Width()为对话框在横向的变化比例
rect.left = rect.left * cx/m_rect.Width();
rect.right = rect.right * cx/m_rect.Width();
rect.top = rect.top * cy/m_rect.Height();
rect.bottom = rect.bottom * cy/m_rect.Height();
pWnd->MoveWindow(rect);
}
}
void CButtonDlg::OnSize(UINT nType, int cx, int cy)
{
CDialog::OnSize(nType, cx, cy);
CWnd* pWnd1 = GetDlgItem(IDC_BUTTON1);
CWnd* pWnd2 = GetDlgItem(IDC_BUTTON2);
CWnd* pWnd3 = GetDlgItem(IDC_BUTTON3);
CWnd* pWnd4 = GetDlgItem(IDC_BUTTON4);
CWnd* pWnd5 = GetDlgItem(IDC_BUTTON5);
modify(pWnd1,cx,cy);
modify(pWnd2,cx,cy);
modify(pWnd3,cx,cy);
modify(pWnd4,cx,cy);
modify(pWnd5,cx,cy);
GetClientRect(&m_rect);//获取新的对话框的大小
}