首页 > 代码库 > 如何限制窗体的移动范围

如何限制窗体的移动范围

作用:

可以控制MessageBox()确认窗口只能在父窗口的范围内移动,不能移出父窗口的范围。

注意:始终要保证子窗口坐标不越界以及维持窗口尺寸大小


方法:重载消息WM_MOVING

//限制窗口的移动范围(不能在WM_MOVE中实现)
void CDelTaskDlg::OnMoving(UINT fwSide, LPRECT pRect)
{
	// TODO:  在此处添加消息处理程序代码

	//获取主窗口坐标
	//方法1:
	CRect rectParent;
	GetParent()->GetWindowRect(&rectParent);
	//方法2:
	//HWND hMain = AfxGetMainWnd()->GetSafeHwnd();
	//::GetWindowRect(hMain, &rectParent);
	//方法3:
	//HWND hMain = AfxGetApp()->GetMainWnd()->GetSafeHwnd();
	//::GetWindowRect(hMain, &rectParent);


  //当前窗口坐标
	CRect rectChild;
	GetWindowRect(&rectChild);

	pRect->left = max(pRect->left, rectParent.left);
	pRect->left = min(pRect->left, rectParent.right - rectChild.Width());

	pRect->top = max(pRect->top, rectParent.top);
	pRect->top = min(pRect->top, rectParent.bottom - rectChild.Height());

	pRect->right = min(pRect->right, rectParent.right);
	pRect->right = max(pRect->right, rectParent.left + rectChild.Width());

	pRect->bottom = min(pRect->bottom, rectParent.bottom);
	pRect->bottom = max(pRect->bottom, rectParent.top + rectChild.Height());

	CDialogEx::OnMoving(fwSide, pRect);
}

或者:


//限制窗口的移动范围(不能在WM_MOVE中实现)
void CDelTaskDlg::OnMoving(UINT fwSide, LPRECT pRect)
{
	// TODO:  在此处添加消息处理程序代码

	CRect rectParent;
	GetParent()->GetWindowRect(&rectParent);

	CRect rectChild;
	GetClientRect(&rectChild);

	//pRect->left = min(pRect->left, rectParent.right - rectChild.Width());
	pRect->left = max(pRect->left, rectParent.left);
	pRect->right = pRect->left + rectChild.Width();

	//pRect->top = min(pRect->top, rectParent.bottom - rectChild.Height());
	pRect->top = max(pRect->top, rectParent.top);
	pRect->bottom = pRect->top + rectChild.Height();

	pRect->right = min(pRect->right, rectParent.right);
	pRect->left = pRect->right - rectChild.Width();

	pRect->bottom = min(pRect->bottom, rectParent.bottom);
	pRect->top = pRect->bottom - rectChild.Height();

	CDialogEx::OnMoving(fwSide, pRect);
}


如何限制窗体的移动范围