MFC 所有控件随窗口大小自适应

1.在头文件中添加

public:
	afx_msg void OnSize(UINT nType, int cx, int cy);
	void ReSize(void);
	POINT old;

2.

BOOL CWVKeyAutoWRDlg::OnInitDialog()
{
	CDialogEx::OnInitDialog();
 
 
//此处代码
	CRect rect;    
	GetClientRect(&rect);     //取客户区大小  
	old.x=rect.right-rect.left;
	old.y=rect.bottom-rect.top;
	int cx = GetSystemMetrics(SM_CXFULLSCREEN);
	int cy = GetSystemMetrics(SM_CYFULLSCREEN);
	CRect rt;
	SystemParametersInfo(SPI_GETWORKAREA,0,&rt,0);
	cy = rt.bottom;
	MoveWindow(0, 0, cx, cy);
 
 
 
 
	return TRUE;  // 除非将焦点设置到控件,否则返回 TRUE
}

3.

void CWVKeyAutoWRDlg::ReSize(void)
{
	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;
}

PS:代码打上没效果的同学,可以在控件可视化界面右键点击控件,选择“属性”,在属性列表有个“动态布局”栏,里面有个“调整大小类型”,选择“两者”,控件就可以实现随窗口大小动态改变尺寸了。如果还不可以,试试这个链接代码(我就是用这个代码起效果了):http://www.cnblogs.com/jack-jia-moonew/p/4157346.html

你可能感兴趣的:(MFC基础编程)