萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

MFC 對話框控件隨窗口大小自適應調整

方案一:控件大小與位置同比例縮放

1. 成員變量記錄初始客戶區

class CMyDialog : public CDialog
{
    CRect m_rectInit; // 初始客戶區大小
    // ...
};

2. OnInitDialog 保存初始大小

BOOL CMyDialog::OnInitDialog()
{
    CDialog::OnInitDialog();
    GetClientRect(&m_rectInit);
    return TRUE;
}

3. OnSize 響應縮放

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)或自定義佈局管理器。
copyright © 萬盛學電腦網 all rights reserved