您的位置:首页 > 其它

MFC中子窗口中的控件随着父窗口的改变而改变

2016-10-17 16:22 232 查看
最近遇到一个比较头疼的问题就是子窗口中的控件无法跟随父窗口的改变而改变,今天终于解决这个问题了,写下解决的方法。

主要的思路就是重写onsize函数,然后向子窗口发送MoveWindow函数。代码为:

 在 主窗口的.h文件中添加:

POINT Old;
void resize();

    并加载OnSize函数 afx_msg void OnSize(UINT nType, int cx, int cy);

  在主窗口的.cpp文件中添加:

void C***Dlg::OnSize(UINT nType, int cx, int cy)

{
CDialogEx::OnSize(nType, cx, cy);
if(nType==SIZE_RESTORED||nType==SIZE_MAXIMIZED)
{
resize();
CRect r;
GetClientRect(&r);
r.DeflateRect(10,10,170,10);//根据需求改变大小
PhotoDlg->MoveWindow(&r,TRUE);
MultiaDlg->MoveWindow(&r,TRUE);
IntroduceDlg->MoveWindow(&r,TRUE);
CompanyDlg->MoveWindow(&r,TRUE);
ControlDlg->MoveWindow(&r,TRUE);//这里有5个子窗口,属性都是child
}

}

void C***Dlg::resize()

{
float fsp[2];
POINT Newp; //获取现在对话框的大小
CRect recta;    
GetClientRect(&recta);     //取客户区大小  
Newp.x=recta.right-recta.left;
Newp.y=recta.bottom-recta.top;
fsp[0]=(float)Newp.x/Old.x;
fsp[1]=(float)Newp.y/Old.y;
CRect Rect;
int woc;
CPoint OldTLPoint,TLPoint; //左上角
CPoint OldBRPoint,BRPoint; //右下角
HWND  hwndChild=::GetWindow(m_hWnd,GW_CHILD);  //列出所有控件  
while(hwndChild)    
{    
woc=::GetDlgCtrlID(hwndChild);//取得ID
GetDlgItem(woc)->GetWindowRect(Rect);  
ScreenToClient(Rect);  
OldTLPoint = Rect.TopLeft();  
TLPoint.x = long(OldTLPoint.x*fsp[0]);  
TLPoint.y = long(OldTLPoint.y*fsp[1]);  
OldBRPoint = Rect.BottomRight();  
BRPoint.x = long(OldBRPoint.x *fsp[0]);  
BRPoint.y = long(OldBRPoint.y *fsp[1]);  
Rect.SetRect(TLPoint,BRPoint);  
GetDlgItem(woc)->MoveWindow(Rect,TRUE);
hwndChild=::GetWindow(hwndChild, GW_HWNDNEXT);    
}
Old=Newp;

}

5个子窗口添加的函数都是一样的,以一个为例:

在子窗口的.h文件中添加:

POINT Old;
void resize();

并加载OnSize函数 afx_msg void OnSize(UINT nType, int cx, int cy);

在子窗口的.cpp文件中添加:

void C~~~Dlg::OnSize(UINT nType, int cx, int cy)

{
CDialogEx::OnSize(nType, cx, cy);
if(nType==SIZE_RESTORED||nType==SIZE_MAXIMIZED)
{
resize();
}

}

void C~~~Dlg::resize()

{
float fsp[2];
POINT Newp; //获取现在对话框的大小
CRect recta;    
GetClientRect(&recta);     //取客户区大小  
Newp.x=recta.right-recta.left;
Newp.y=recta.bottom-recta.top;
fsp[0]=(float)Newp.x/Old.x;
fsp[1]=(float)Newp.y/Old.y;
CRect Rect;
int woc;
CPoint OldTLPoint,TLPoint; //左上角
CPoint OldBRPoint,BRPoint; //右下角
HWND  hwndChild=::GetWindow(m_hWnd,GW_CHILD);  //列出所有控件  
while(hwndChild)    
{    
woc=::GetDlgCtrlID(hwndChild);//取得ID
GetDlgItem(woc)->GetWindowRect(Rect);  
ScreenToClient(Rect);  
OldTLPoint = Rect.TopLeft();  
TLPoint.x = long(OldTLPoint.x*fsp[0]);  
TLPoint.y = long(OldTLPoint.y*fsp[1]);  
OldBRPoint = Rect.BottomRight();  
BRPoint.x = long(OldBRPoint.x *fsp[0]);  
BRPoint.y = long(OldBRPoint.y *fsp[1]);  
Rect.SetRect(TLPoint,BRPoint);  
GetDlgItem(woc)->MoveWindow(Rect,TRUE);
hwndChild=::GetWindow(hwndChild, GW_HWNDNEXT);    
}
Old=Newp;

}

主窗口与子窗口添加的内容比较类似,这样当点击最大化按钮时,子窗口也会跟随父窗口的改变而改变
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: