65.9K
CodeProject 正在变化。 阅读更多。
Home

有界矩形

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.59/5 (5投票s)

2008年1月18日

CPOL

1分钟阅读

viewsIcon

19998

downloadIcon

195

关于如何将窗口的位置限制在限定矩形内的简要讨论。

引言

对于大多数应用程序,拖动窗口在屏幕上应该几乎不受限制。然而,在某些情况下,你可能希望将窗口限制在某个限定矩形内。 在本文中,我将介绍完成此操作所需的所有步骤(两者!)。

步骤 1

我们需要做的第一件事是确定窗口的初始大小,这样当我们进行步骤 2 中的窗口位置调整时,就不会在过程中意外更改其大小。 因此,在对话框的 OnInitDialog() 方法中,只需调用 GetWindowRect() 即可,例如

SetOwner(CWnd::GetDesktopWindow());

CRect rc;
GetWindowRect(rc);
m_nWidth = rc.Width(); // member variables of the dialog
m_nHeight = rc.Height();

第二步

第二(也是最后)一步是为 WM_MOVING 消息创建一个处理程序函数。 在该函数中,我们首先需要获取父窗口(限定矩形)的位置。 然后,我们通过确保对话框的四个边落在父窗口的每个边内来调整(子)对话框的四个边。 它看起来有点“数学化”,但实际上非常简单明了。

CRect rcParent;
GetOwner()->GetWindowRect(rcParent);

// keep the child's left edge inside the parent's right edge
pRect->left = min(pRect->left, rcParent.right - m_nWidth);
// keep the child's left edge inside the parent's left edge
pRect->left = max(pRect->left, rcParent.left);

// keep the child's top edge inside the parent's bottom edge    
pRect->top = min(pRect->top, rcParent.bottom - m_nHeight);
// keep the child's top edge inside the parent's top edge
pRect->top = max(pRect->top, rcParent.top);

// keep the child's right edge inside the parent's right edge
pRect->right = min(pRect->right, rcParent.right);
// keep the child's right edge inside the parent's left edge
pRect->right = max(pRect->right, rcParent.left + m_nWidth);

// keep the child's bottom edge inside the parent's bottom edge
pRect->bottom = min(pRect->bottom, rcParent.bottom);
// keep the child's bottom edge inside the parent's top edge
pRect->bottom = max(pRect->bottom, rcParent.top + m_nHeight);

这就是它的全部内容。

摘要

虽然我的示例使用了由桌面拥有且是模态的对话框,但相同的代码可以用于诸如由其应用程序拥有的“关于”框,或 MDI 应用程序中的框架等情况。 唯一的区别在于被限制的窗口的父窗口/所有者。

尽情享用!

© . All rights reserved.