MFC small note: Control window with the changes

First, demand

When the window size changes, such as maximized, minimized, and controls the position and the size does not change, herein implement this functionality.

Second, the interface

The main interface is a dialog with minimize, maximize, close the other functions.

Third, the principle

When the window is changed responsive OnSize function, and calculate the position of the controls, scaled.

Fourth, the coding

4.1 Variable Definition

Add WM_SIZE message in the dialog class wizard. Its function is defined as follows:

afx_msg void OnSize(UINT nType, int cx, int cy);

In the dialog header file to declare variables:

CRect m_cRect;

For saving location information.

4.2 Initialization

To obtain location information OnInitDialog function and save:

GetClientRect(&m_cRect);

Zoom to achieve 4.3

Calculated in the same document, implement controls change the code as follows:

void CTestDlg::ChangeSize(int ctrID, int cx, int cy)
{
    CWnd* pWnd = GetDlgItem(ctrID);
    if (pWnd)
    {
        CRect rect;   //获取控件变化前的大小  
        pWnd->GetWindowRect(&rect);
        ScreenToClient(&rect);//将控件大小转换为在对话框中的区域坐标

        // cx/m_cRect.Width()为对话框在横向的变化比例
        rect.left = rect.left*cx / m_cRect.Width();//调整控件大小
        rect.right = rect.right*cx / m_cRect.Width();
        rect.top = rect.top*cy / m_cRect.Height();
        rect.bottom = rect.bottom*cy / m_cRect.Height();
        pWnd->MoveWindow(rect);//设置控件大小
    }
}

Acquiring first control ID, to obtain the size of the control, then according to the current x, y ratio is calculated, then control is moved.

4.4 OnSize event processing

Call ChangeSize function OnSize function:

void CTestDlg::OnSize(UINT nType, int cx, int cy)
{
    CDialogEx::OnSize(nType, cx, cy);

    int CDlgItem[] = {
        IDC_STC_1,
        IDC_STC_2,
        IDC_STC_3,
        };

    for (int i = 0; i < sizeof(CDlgItem) / sizeof(CDlgItem[0]); i++)
    {
        ChangeSize(CDlgItem[i], cx, cy);
    }
    GetClientRect(&m_cRect);// 将变化后的对话框大小设为旧大小
}

Scaled to the specified control ID. Note that some controls can not be scaled, for example, the top left of the prompt-related controls, no need to move.

Published 481 original articles · won praise 244 · Views 1.1 million +

Guess you like

Origin blog.csdn.net/subfate/article/details/103740804