0

I'm attempting to make a custom control that properly draws itself to fill its current size. I was under the assumption that I should use the ClientRectangle property for sizing, but the right and bottom of the client rectangle seem to be getting clipped.

Filling the draw event handler with

Rectangle smaller = new Rectangle(5, 5, ClientRectangle.Width - 10, ClientRectangle.Height - 10);
e.Graphics.DrawRectangle(System.Drawing.Pens.Black, smaller);  
e.Graphics.DrawRectangle(System.Drawing.Pens.Red, ClientRectangle);

yields this:

ClientRecangle is clipped

What should I be using to get the drawable area of the control?

Matt Kline
  • 10,149
  • 7
  • 50
  • 87
  • 1
    possible duplicate: http://stackoverflow.com/a/8377709/577417 – Benjamin Gale Dec 13 '12 at 16:41
  • possible duplicate of [Pixel behaviour of FillRectangle and DrawRectangle](http://stackoverflow.com/questions/3147569/pixel-behaviour-of-fillrectangle-and-drawrectangle) – Simon Mourier Dec 13 '12 at 16:46
  • @Benjamin The answer from the possible duplicate seems _almost_ correct. It seems that you need to subtract 2, not 1, from the bottom and right. – Matt Kline Dec 13 '12 at 16:59

1 Answers1

2

You can either use:

ControlPaint.DrawBorder(g, this.ClientRectangle, _
                        Color.Red, ButtonBorderStyle.Solid);

where Graphics g = e.Graphics;.

Or draw it as you did but subtracting 1 from width and height (1 because width and height are inclusive but draw rectangle needs the size exclusive the last pixel - internally it calculates x + w/y + h which then ends up at the position for the next pixel after the last, hence we need to subtract one to get the position for the last pixel).

rectangle r = this.ClientRectangle;
r.Width -= 1;
r.Height -= 1;

g.DrawRectangle(System.Drawing.Pens.Red, r);

And of course this from within the OnPaint event handler.