在单文档应用程序中,有一种基于CFormView视图的实现,类似于Dialog对话框,可以通过工具栏(ToolBox)添加空间,但是通过这种方法添加的控件无法随着窗口的扩大或者缩小而改变自己的位置与大小,在这里介绍一种实现控件位置与大小随窗口的变化而改变的方法。
首先,在View视图的派生类中添加成员变量m_rect:
class CMyView : public CFormView
{
………………相关代码………………
protected:
CRect m_rect;
………………相关代码………………
};
然后,在相应的cpp文件中的OnInitialUpdate()函数中对m_rect进行初始化
void CMyView::OnInitialUpdate()
{
CFormView::OnInitialUpdate();
GetParentFrame()->RecalcLayout();
ResizeParentToFit();
GetClientRect (&m_rect);
…………相关代码…………
}
接下来,在CMyView类中对消息WM_SIZE进行响应并添加消息处理函数OnSize(),而控件的变化在消息处理函数中进行
void CMyView::OnSize(UINT nType, int cx, int cy)
{
CFormView::OnSize(nType, cx, cy);
// TODO: Add your message handler code here
CWnd *pWnd;
pWnd = GetDlgItem (IDC_STOP);//获取控件句柄
//应用程序初始化的时也要调用该函数,此时窗口还未创建m_rect,判断程序是否启动,if((m_rect.Width ()!=0)&&(m_rect.Height ()!=0)&&nType==SIZE_RESTORED || nType==SIZE_MAXIMIZED){CRect lstrect,editrct,okrct,cancelrct;//获取控件变化前大小pListWnd->GetWindowRect(&lstrect);pEditWnd->GetWindowRect (&editrct);pOKWnd->GetWindowRect (&okrct);pCancelWnd->GetWindowRect (&cancelrct);//将控件大小转换为在对话框中的区域坐标ScreenToClient(&lstrect);ScreenToClient (&editrct);ScreenToClient (&okrct);ScreenToClient (&cancelrct);// cx/m_rect.Width()为对话框在横向的变化比例lstrect.left=lstrect.left*cx/m_rect.Width();//调整控件大小lstrect.right=lstrect.right*cx/m_rect.Width();lstrect.top=lstrect.top*cy/m_rect.Height();lstrect.bottom=lstrect.bottom*cy/m_rect.Height();pListWnd->MoveWindow(lstrect);//设置控件大小editrct.left = editrct.left*cx/m_rect.Width ();editrct.right=editrct.right*cx/m_rect.Width();editrct.top=editrct.top*cy/m_rect.Height();editrct.bottom=editrct.bottom*cy/m_rect.Height();pEditWnd->MoveWindow (editrct);okrct.left = okrct.left*cx/m_rect.Width ();okrct.right= okrct.right*cx/m_rect.Width();okrct.top= okrct.top*cy/m_rect.Height();okrct.bottom= okrct.bottom*cy/m_rect.Height();pOKWnd->MoveWindow (okrct);cancelrct.left = cancelrct.left*cx/m_rect.Width ();cancelrct.right= cancelrct.right*cx/m_rect.Width();cancelrct.top= cancelrct.top*cy/m_rect.Height();cancelrct.bottom= cancelrct.bottom*cy/m_rect.Height();pCancelWnd->MoveWindow (cancelrct);GetClientRect (&m_rect);}}