class CMyDialog : public CDialog
{
CRect m_rectInit; // 初始客戶區大小
// ...
};
BOOL CMyDialog::OnInitDialog()
{
CDialog::OnInitDialog();
GetClientRect(&m_rectInit);
return TRUE;
}
void CMyDialog::OnSize(UINT nType, int cx, int cy)
{
CDialog::OnSize(nType, cx, cy);
if (nType == SIZE_MINIMIZED) return; // 最小化不處理
// 遍歷需調整的控件 ID
const int ids[] = { IDC_TREE, IDC_EDIT1, IDC_BTN_OK, /*...*/ };
for (int id : ids)
{
CWnd* pWnd = GetDlgItem(id);
if (pWnd) ResizeControl(pWnd, cx, cy);
}
GetClientRect(&m_rectInit); // 更新基準大小
}
void CMyDialog::ResizeControl(CWnd* pWnd, int cx, int cy)
{
CRect rc;
pWnd->GetWindowRect(&rc);
ScreenToClient(&rc);
// 按比例計算新位置
rc.left = rc.left * cx / m_rectInit.Width();
rc.right = rc.right * cx / m_rectInit.Width();
rc.top = rc.top * cy / m_rectInit.Height();
rc.bottom = rc.bottom * cy / m_rectInit.Height();
pWnd->MoveWindow(&rc);
}
適用於按鈕、標簽等固定尺寸控件,保持與右/底邊距恒定。
void CMyDialog::OnSize(UINT nType, int cx, int cy)
{
CDialog::OnSize(nType, cx, cy);
if (nType == SIZE_MINIMIZED) return;
CWnd* pBtn = GetDlgItem(IDC_BUTTON1);
if (pBtn)
{
CRect rc; pBtn->GetWindowRect(&rc); ScreenToClient(&rc);
int dx = m_rectInit.Width() - rc.right; // 原右邊距
int dy = m_rectInit.Height() - rc.bottom; // 原底邊距
rc.left = cx - rc.Width() - dx;
rc.right = cx - dx;
rc.top = cy - rc.Height() - dy;
rc.bottom = cy - dy;
pBtn->MoveWindow(&rc);
}
GetClientRect(&m_rectInit);
}
OnSize 首行判斷 SIZE_MINIMIZED,否則最小化還原會導致控件錯位。m_rectInit 必須在 OnInitDialog 中獲取,而非構造函數。CMFCLayout)或自定義佈局管理器。