How to set a new height (or width) to a CRect?

68 Views Asked by At

How do you change the height (or width) of a MFC CRect, without moving the rectangle (top left static) ?

It seems there is no direct setter to the (calculated) height ( int CRect::Height() ).

The current way I find is to recalculate the bottom:

// Create a 40 x 40 rectangle
CRect myRect(10, 10, 50, 50);
// Set the Height to 80
myRect.bottom = myRect.top + 80;
1

There are 1 best solutions below

1
IInspectable On

A RECT in Windows programming is a structure that stores values for left, top, right, and bottom (conventionally endpoint exclusive). The width and height are derived values (right - left and bottom - top, respectively).

There is no API to change the width (or height) directly since that would be an ambiguous operation: Should a hypothetical SetWidth() API grow or shrink towards the left? The right? Or maintain the center?

MFC's CRect class merely encapsulates a RECT and provides some convenience members (such as Height()) but not much more. If you want to increase the height of a CRect either add to its bottom or subtract from its top. If you want to set the height to a specific value update the value opposite to the one you wish to keep stable (as you're doing in the question already).

Calling NormalizeRect() is a good idea if you cannot otherwise ensure that left is less than or equal to right and top is less than or equal to bottom.