How do I draw a border around a ToolStripButton

2.5k Views Asked by At

I have a ToolStripButton inside a ToolStrip that I want to draw a border around. This is the code I am using:

    private void tsbtnSearch_Paint(object sender, PaintEventArgs e)
    {
        ToolStripButton btn = (ToolStripButton)sender;

        ControlPaint.DrawBorder(e.Graphics, btn.Bounds,
               Color.Red, 3, ButtonBorderStyle.Outset,
               Color.Red, 3, ButtonBorderStyle.Outset,
               Color.Red, 3, ButtonBorderStyle.Outset,
               Color.Red, 3, ButtonBorderStyle.Outset);

    }

The border is being drawn as shown in the image below:

ToolStripButton

What do I need to do to get the coordinates correct?

1

There are 1 best solutions below

0
On

You are almost there. You can use the simpler variant of DrawBorder and define the rectangle of the border manually using the button widht and height:

       ToolStripButton btn = (ToolStripButton)sender;
                ControlPaint.DrawBorder(
                       e.Graphics, 
                       new Rectangle(0, 0, btn.Width, btn.Height),
// or as @LarsTech commented, this works fine too!
//  btn.ContentRectangle,
                       Color.Red,
                       ButtonBorderStyle.Solid);            

The rectangle of the border is not the bounds of the button in this case (IMO, because the ToolStripButtonis not a flat button, but a complex object ToolStripItem, that has more than just the button).

enter image description here