天天看点

实现MFC 对话框最大化时控件也随比例最大化或者还原

第一步、在对话框类中(.h文件)定义如下变量和函数

[cpp]  view plain  copy

  1. void ReSize();  
  2. POINT old;  

[cpp]  view plain  copy

  1. afx_msg void OnSize(UINT nType, int cx, int cy);  

第二步、在OnInitDialog()中 计算出原始对话框的大小

[cpp]  view plain  copy

  1. CRect rect;      
  2. GetClientRect(&rect);     //取客户区大小    
  3. old.x=rect.right-rect.left;  
  4. old.y=rect.bottom-rect.top;  

第三步、添加 WM_SIZE消息

[cpp]  view plain  copy

  1. void CStuDemoDlg::OnSize(UINT nType, int cx, int cy)   
  2. {  
  3.     CDialog::OnSize(nType, cx, cy);  
  4.     // TODO: Add your message handler code here  
  5.     if (nType==SIZE_RESTORED||nType==SIZE_MAXIMIZED)  
  6.     {  
  7.         ReSize();  
  8.     }  
  9. }  

第四步、刷新控件函数

[cpp]  view plain  copy

  1. void CStuDemoDlg::ReSize()  
  2. {  
  3.     float fsp[2];  
  4.     POINT Newp; //获取现在对话框的大小  
  5.     CRect recta;      
  6.     GetClientRect(&recta);     //取客户区大小    
  7.     Newp.x=recta.right-recta.left;  
  8.     Newp.y=recta.bottom-recta.top;  
  9.     fsp[0]=(float)Newp.x/old.x;  
  10.     fsp[1]=(float)Newp.y/old.y;  
  11.     CRect Rect;  
  12.     int woc;  
  13.     CPoint OldTLPoint,TLPoint; //左上角  
  14.     CPoint OldBRPoint,BRPoint; //右下角  
  15.     HWND  hwndChild=::GetWindow(m_hWnd,GW_CHILD);  //列出所有控件    
  16.     while(hwndChild)      
  17.     {      
  18.         woc=::GetDlgCtrlID(hwndChild);//取得ID  
  19.         GetDlgItem(woc)->GetWindowRect(Rect);    
  20.         ScreenToClient(Rect);    
  21.         OldTLPoint = Rect.TopLeft();    
  22.         TLPoint.x = long(OldTLPoint.x*fsp[0]);    
  23.         TLPoint.y = long(OldTLPoint.y*fsp[1]);    
  24.         OldBRPoint = Rect.BottomRight();    
  25.         BRPoint.x = long(OldBRPoint.x *fsp[0]);    
  26.         BRPoint.y = long(OldBRPoint.y *fsp[1]);    
  27.         Rect.SetRect(TLPoint,BRPoint);    
  28.         GetDlgItem(woc)->MoveWindow(Rect,TRUE);  
  29.         hwndChild=::GetWindow(hwndChild, GW_HWNDNEXT);      
  30.     }  
  31.     old=Newp;  
  32. }