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++面向对象编程
开发语言·c++
啦啦啦啦啦zzzz1 小时前
设计模式:桥接模式和组合模式
c++·设计模式·组合模式·桥接模式
-森屿安年-1 小时前
647. 回文子串
c++·算法·动态规划
fpcc1 小时前
c++应用网络编程之十七WebSocket
网络·c++·websocket
haolin123.1 小时前
类和对象(下)
c语言·开发语言·c++
皓月斯语1 小时前
P5736 【深基7.例2】质数筛
c++·算法·题解
鸿芯微控科技2 小时前
MFC质量流量控制器流量不准怎么排查?设定值、反馈值与参考流量对比,附Python代码
c++·python·mfc
拂拉氏2 小时前
【知识讲解】 让指针拥有“自我意识”?--C++智能指针相关内容讲解
c++·智能指针
CVer儿2 小时前
c++二级指针
开发语言·c++
mlidongfeng3 小时前
[AI][C++26] SIMD 编程模型思考
开发语言·c++·人工智能