天天看點

VC++控件自适應螢幕的方法

1.首先在初始化函數中,FormView在OnInitialUpdate(),Dialog在OnInitDialog()中初始化控件的大小。

//開始初始化控件大小
 m_IsInitialed = false;
 CRect m_ClientRect;
 this->GetClientRect(&m_ClientRect);
 CSize m_Forsize;
 m_Forsize = GetTotalSize();//在資源編輯器中定好大小後,程式運作時大小(不管最大化和最小化,該大小均為同一個值),客戶區大于或等于顯示的大小
 double m_x = (double)m_ClientRect.Width() / m_Forsize.cx;//寬度方向發大倍數
 double m_y = (double)m_ClientRect.Height() / m_Forsize.cy;//高度方向發大倍數
 //調整控件的大小
 CWnd *pWnd = NULL; 
 pWnd = GetWindow(GW_CHILD);
 while(pWnd)//判斷是否為空,因為對話框建立時會調用此函數,而當時控件還未建立
 {
  CRect rect;   //擷取控件變化前大小
  pWnd->GetWindowRect(&rect);
  ScreenToClient(&rect);//将控件大小轉換為在對話框中的區域坐标
  m_ControlRect.insert(pair<int, CRect>(pWnd->GetDlgCtrlID(), rect));//儲存控件的初始大小,以便在OnSize函數中繼續使用
  int width = rect.Width();
  int height = rect.Height();
  WCHAR szBuf[256];
  GetClassName(pWnd->m_hWnd,szBuf,256);         
  if( _tcsicmp(szBuf,_T("Edit")) == 0)   
  { 
   //Edit隻是位置變化,大小沒有變
   rect.top = m_y * rect.top;
   rect.left = m_x * rect.left;
   rect.bottom = rect.top + height;
   rect.right = rect.left + width;
  }
  else
  {
   //其它控件位置和大小均變化
   rect.top = m_y * rect.top;
   rect.left = m_x * rect.left;
   rect.bottom = m_y * rect.bottom;
   rect.right = m_x * rect.right;
  }
  pWnd->MoveWindow(&rect);//設定控件大小
  pWnd = pWnd->GetWindow(GW_HWNDNEXT);
 }
 
 //控件初始化結束
 m_IsInitialed = true;
           

2.如果界面在運作時大小可以改變,則在OnSize函數中加入如下代碼

// TODO: 在此處添加消息處理程式代碼
	CFormView::ShowScrollBar(SB_BOTH, false);//設定沒有滾動條,視情況而定。
         //在界面不是最小化并且已經初始化完畢
	if (!IsIconic() && m_IsInitialed)
	{
		CSize m_Forsize;
		m_Forsize = GetTotalSize();
		double m_x = (double)cx / m_Forsize.cx;
		double m_y = (double)cy / m_Forsize.cy;
                //讀取控件的初始大小
		map<int, CRect>::iterator pos = m_ControlRect.begin();
		for (; pos != m_ControlRect.end(); ++pos)
		{
			CRect rect = pos->second;
			int width = rect.Width();
			int height = rect.Height();
			WCHAR szBuf[256];
			GetClassName(GetDlgItem(pos->first)->m_hWnd,szBuf,256);     				
			if( _tcsicmp(szBuf,_T("Edit")) == 0)   
			{ 
				rect.top = m_y * rect.top;
				rect.left = m_x * rect.left;
				rect.bottom = rect.top + height;
				rect.right = rect.left + width;
			}
			else
			{
				rect.top = m_y * rect.top;
				rect.left = m_x * rect.left;
				rect.bottom = m_y * rect.bottom;
				rect.right = m_x * rect.right;
			}
			GetDlgItem(pos->first)->MoveWindow(rect);
		}
	}
           

或在OnShowWindow()函數中加入也可以(特别是在對話框作為tabpage時)

http://blog.csdn.net/ybw20041910/article/details/5679730

繼續閱讀