Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Bounded rectangles

0.00/5 (No votes)
18 Jan 2008 1  
A very brief discussion on how to restrict a window's position to a bounding rectangle.

Introduction

For most applications, dragging a window around on the screen should be mostly uninhibited. There are, however, a few scenarios where you may want to restrict the window to some bounding rectangle. In this article, I'll lay out all of the steps necessary (both of them!) to accomplish this.

Step 1

The first thing we need to do is figure out the initial size of our window so when we go to adjust the window's position in step 2, we don't accidently change its size in the process. So, in the dialog's OnInitDialog() method, simply make a call to GetWindowRect() like:

SetOwner(CWnd::GetDesktopWindow());

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

Step 2

The second (and final) step is to create a handler function for the WM_MOVING message. In that function, we first need to get the position of the parent (bounding) rectangle. Then, we adjust the (child) dialog's four sides by ensuring they fall within each side of the parent. It looks sort of "mathy," but it's really straightforward.

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);

That's all there is to it.

Summary

While my example used a modal dialog owned by the desktop, this same code can be employed in situations such as an About box owned by its application, or a frame within an MDI application. The only difference lies in the parent/owner of the window being restricted.

Enjoy!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here