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;
        }
    }
}

四.效果如下

原始:

最大化(全屏):

相关推荐
让我们一起加油好吗18 分钟前
【C++】封装红黑树模拟实现 set 和 map
linux·c++·set·map·红黑树
hsjkdhs24 分钟前
C++之类的继承与派生
开发语言·c++
冷徹 .33 分钟前
2024ICPC区域赛香港站
数据结构·c++·算法
沐怡旸1 小时前
【底层机制】std:: function 解决的痛点?是什么?如何实现?如何正确用?
c++·面试
浅川.251 小时前
xtuoj string
开发语言·c++·算法
Larry_Yanan3 小时前
QML学习笔记(三十)QML的布局器(Layouts)
c++·笔记·qt·学习·ui
筱砚.3 小时前
【C++——面向对象编程综合案例】
c++
ajassi20003 小时前
开源 C++ QT QML 开发(十五)通讯--http下载
c++·qt·开源
我梦之63 小时前
libevent输出缓存区的数据
服务器·网络·c++·缓存
磨十三3 小时前
C++ 单例模式(Singleton)详解
c++·单例模式