MFC中当我们添加了很多控件后,布局就是一个很难控制的方面,当程序运行在不能的PC上就会有不一样的布局,如何解决呢方法很多,我第一次是自己算出控件的位置,然后按照比例缩放,但是方法很麻烦,还不易控制,后来一个同事用如下代码很容易实现,非常不错分享给大家:
1. *.h 添加消息
- 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;