MFC实现对话框与控件的自适应调节

一.对话框属性设置

先将对话框的Border属性由Dialog Frame设置为Resizing。

二.添加消息处理函数

类向导 -> 消息(WM-SIZE)添加处理函数->void COnshowDlg::OnSize(UINT nType, int cx, int cy)。

三.添加代码

在.h文件中声明:

cpp 复制代码
void ResizeUI();

vector<CRect> m_vec_rect_;

源文件:

cpp 复制代码
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();
    }   
 
}
cpp 复制代码
void COnshowDlg::OnSize(UINT nType, int cx, int cy)
{
    CBCGPDialog::OnSize(nType, cx, cy);
    if(nType != SIZE_MINIMIZED)
    {
        ResizeUI();
    }
}
cpp 复制代码
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;
        }
    }
}

四.效果如下

原始:

最大化(全屏):

相关推荐
L_09073 小时前
【C++】异常
开发语言·c++
liulilittle3 小时前
关于拥塞控制的几点思考
网络·c++·tcp/ip·计算机网络·信息与通信·tcp·通信
QT-Neal5 小时前
C++ 编码规范
c++
啦啦啦啦啦zzzz6 小时前
数据结构:红黑树理论
数据结构·c++·红黑树
Yolo_TvT6 小时前
C++:默认构造函数
c++
小欣加油7 小时前
leetcode994 腐烂的橘子
数据结构·c++·算法·leetcode·bfs
.千余8 小时前
【C++】手写双向链表:list容器模拟实现
开发语言·c++·笔记·学习·其他
liulilittle9 小时前
过冲:拥塞控制的呼吸与盲行
linux·网络·c++·tcp/ip·计算机网络·tcp·通信
小欣加油9 小时前
leetcode2574 左右元素和的差值
数据结构·c++·算法·leetcode·职场和发展
weixin_461769409 小时前
通过数组和队列构造二叉树方法(用于算法测试),C++ vector不能直接使用null
数据结构·c++·算法·vector·nullptr·null