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

四.效果如下

原始:

最大化(全屏):

相关推荐
fqbqrr1 天前
2601C++,模块基础
c++
带土11 天前
6. C++智能指针(1)
开发语言·c++
星火开发设计1 天前
C++ queue 全面解析与实战指南
java·开发语言·数据结构·c++·学习·知识·队列
橘颂TA1 天前
【剑斩OFFER】算法的暴力美学——力扣 394 题:字符串解码
数据结构·c++·结构与算法
txinyu的博客1 天前
结合游戏场景理解,互斥锁,读写锁,自旋锁,CAS / 原子变量,分段锁
开发语言·c++·游戏
hugerat1 天前
在AI的帮助下,用C++构造微型http server
linux·c++·人工智能·http·嵌入式·嵌入式linux
-森屿安年-1 天前
unordered_map 和 unordered_set 的实现
数据结构·c++·散列表
九久。1 天前
手动实现std:iterator/std:string/std::vector/std::list/std::map/std:set
c++·stl
小羊羊Python1 天前
Sound Maze - 基于 SFML+C++14 的音效迷宫开源游戏 | MIT 协议
c++·游戏·开源
txinyu的博客1 天前
HTTP服务实现用户级窗口限流
开发语言·c++·分布式·网络协议·http