0

I'm trying to do a bit of painting on my Winform controls through the Paint event because why not. I've got this hooked up, because StackOverlfow told me it would work:

private void PaintLines(object sender, PaintEventArgs e)
{
    ControlPaint.DrawBorder(e.Graphics, ClientRectangle,
                    Color.Gray, 1, ButtonBorderStyle.Solid,
                    Color.Gray, 1, ButtonBorderStyle.Solid,
                    Color.Gray, 1, ButtonBorderStyle.Solid,
                    Color.Gray, 1, ButtonBorderStyle.Solid);
}

The problem is that only works for top and left borders, not right or bottom. Here's the Designer.cs because I suspect it's a problem with how the control is set.

this.lblOffset.AutoSize = true;
this.lblOffset.Dock = System.Windows.Forms.DockStyle.Fill;
this.lblOffset.Location = new System.Drawing.Point(3, 25);
this.lblOffset.Name = "lblOffset";
this.lblOffset.Size = new System.Drawing.Size(114, 25);
this.lblOffset.TabIndex = 1;
this.lblOffset.Text = "Offset (V)";
this.lblOffset.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
this.lblOffset.Paint += new System.Windows.Forms.PaintEventHandler(PaintLines);

So the question is how do I get my four borders painted?

dymanoid
  • 14,771
  • 4
  • 36
  • 64
AmiralPatate
  • 125
  • 1
  • 7
  • 1
    There is a old peculiarity/bug in DrawRectangle, which makes it overdraw to the right&bottom by 1 pixel. It is probably used in the DrawBorder as well; so you will need to feed in rectangles 1 pixel less high&wide. Many discussions, e.g. [here](https://blogs.msdn.microsoft.com/oldnewthing/20040218-00/?p=40563) or [here](https://stackoverflow.com/questions/3147569/pixel-behaviour-of-fillrectangle-and-drawrectangle) etc... – TaW May 02 '18 at 15:16
  • 1
    ControlPaint.DrawBorder() already assumes it must draw the rectangle 1 pixel smaller. Passing the form's ClientRectangle property is the bug. – Hans Passant May 02 '18 at 16:10

1 Answers1

4

You're using incorrect ClientRectangle - the one of the whole form. Thus, the Width and Height values of that rectangle don't fit into the Label's client rectangle.

Use the Label's ClientRectangle instead:

ControlPaint.DrawBorder(e.Graphics, lblOffset.ClientRectangle,
    Color.Gray, 1, ButtonBorderStyle.Solid,
    Color.Gray, 1, ButtonBorderStyle.Solid,
    Color.Gray, 1, ButtonBorderStyle.Solid,
    Color.Gray, 1, ButtonBorderStyle.Solid);
dymanoid
  • 14,771
  • 4
  • 36
  • 64