Code Snippet - MFC调整窗口大小

限制窗口大小

MFC程序的窗口一般可以自由缩放,如需限制窗口的最大/最小尺寸,可以通过响应WM_GETMINMAXINFO消息来实现。

在程序初始化时,获取窗口的默认大小,限制窗口缩放的最小值为其初始尺寸。示例代码如下

DemoDlg.h

CRect rcMainDlg;

DemoDlg.cpp
    
BOOL CDemoDlg::OnInitDialog()
{
    //...

    GetWindowRect(&rcMainDlg);

    //...
}

void CDemoDlg::OnGetMinMaxInfo(MINMAXINFO* lpMMI)
{
    lpMMI->ptMinTrackSize.x = rcMainDlg.Width();
    lpMMI->ptMinTrackSize.y = rcMainDlg.Height();

    CDialogEx::OnGetMinMaxInfo(lpMMI);
}

也可以指定窗口尺寸的绝对值

void CDemoDlg::OnGetMinMaxInfo(MINMAXINFO* lpMMI)
{
    lpMMI->ptMinTrackSize.x = 800;
    lpMMI->ptMinTrackSize.y = 600;
    
    lpMMI->ptMaxTrackSize.x = 1024;
    lpMMI->ptMaxTrackSize.y = 768;

    CDialogEx::OnGetMinMaxInfo(lpMMI);
}

拖动窗口时改变控件大小

对话框窗口中有上下排列的两个控件,上面是一个Botton(IDC_BUTTON1),下面是一个ListBox(IDC_LIST1),要求拖动窗口时动态改变ListBox控件的大小。响应窗口的WM_SIZE消息,示例代码如下

DemoDlg.cpp

void CDemoDlg::OnSize(UINT nType, int cx, int cy)
{
    CDialogEx::OnSize(nType, cx, cy);
    
    CWnd* pListBoxWnd = GetDlgItem(IDC_LIST1);

    if (pListBoxWnd->GetSafeHwnd())
    {
        RECT rcListBox;
        GetWindowRect(&rcListBox);
        ScreenToClient(&rcListBox);

        RECT rcButton;
        ((CButton *)GetDlgItem(IDC_BUTTON1))->GetWindowRect(&rcButton);
        ScreenToClient(&rcButton);

        RECT rcListBoxNew;
        rcListBoxNew.left = rcListBox.left + 5;
        rcListBoxNew.top = rcButton.bottom + 5;
        rcListBoxNew.right = rcListBox.right - 5;
        rcListBoxNew.bottom = rcListBox.bottom - 5;

        pListBoxWnd->MoveWindow(&rcListBoxNew);
    }
}

RECT与CRect

MSDN RECT:
The RECT structure defines a rectangle by the coordinates of its upper-left and lower-right corners.

typedef struct tagRECT {
    LONG left;
    LONG top;
    LONG right;
    LONG bottom;
} RECT, *PRECT, NEAR *NPRECT, FAR *LPRECT;

MSDN CRect:
Similar to a Windows RECT structure.CRect also includes member functions to manipulate CRect objects and Windows RECT structures.A CRect object can be passed as a function parameter wherever a RECT structure, LPCRECT, or LPRECT can be passed.

CRect() throw(); 
CRect(int l, int t, int r, int b) throw(); 
CRect(const RECT& srcRect) throw(); 
CRect(LPCRECT lpSrcRect) throw(); 
CRect(POINT point, SIZE size) throw(); 
CRect(POINT topLeft, POINT bottomRight) throw();

RECT结构体定义矩形的左上角/右下角的坐标,其中left指定了左上角的X坐标,top左上角的Y坐标,right右下角的X坐标,bottom右下角的Y坐标。CRect类有以上六个构造函数,可以直接将一个RECT结构体传给CRect实例

RECT rc1;
CRect rc2 = rc1;

GetWindowRect() GetClientRect()与ScreenToClient()

GetWindowRect()用于获取以屏幕左上角为原点的屏幕坐标系下的RECT
GetClientRect()获取在客户区坐标系下的RECT,以所在窗口左上角为原点,并忽略标题栏,获取到的RECT的left和top永远为0,right和bottom的值即为控件的大小
ScreenToClient()用来将屏幕坐标系下的RECT坐标转换为客户区坐标系下的RECT坐标

参考资料

1. Dialog窗口大小调整控制OnSize/OnSizing
http://blog.csdn.net/chunyexiyu/article/details/9037181

添加新评论