.netimagewinformstoolstripbutton

Resizing ToolStripButtons to fit complete BackGround image


My goal is totally fit image in toolStripButton and toolStripDropDownButton.

If a image in the button set with image property, I can not totally fit the image in the button. Because of margin, border, or something of the button.(I don't know exactly).

So I try to set the image in the button with BackgroudImage property. After I adjust some property(like AutoSize, Size and so on...), I can fit image in button.

but in this case, I can not see background image. It is disappear, when the mouse cursor is located in the button.

How can I solve this problem??

Image Property. I can not remove the gap between images. alt text

BackgroundImage Property. I can not see the image, when mouse cursor is on the image. alt text


Solution

  • Well, you found out why it leaves a space around the Image property. You can customize the rendering of the button by assigning the ToolStrip.Renderer property. That could look something like this:

    public partial class Form1 : Form {
        public Form1() {
            InitializeComponent();
            toolStrip1.Renderer = new MyRenderer();
        }
        private class MyRenderer : ToolStripProfessionalRenderer {
            protected override void OnRenderButtonBackground(ToolStripItemRenderEventArgs e) {
                if (e.Item.BackgroundImage == null) base.OnRenderButtonBackground(e);
                else {
                    Rectangle bounds = new Rectangle(Point.Empty, e.Item.Size);
                    e.Graphics.DrawImage(e.Item.BackgroundImage, bounds);
                    if (e.Item.Pressed) {
                        // Something...
                    }
                    else if (e.Item.Selected) {
                        // Something...
                    }
                    using (Pen pen = new Pen(Color.Black)) {
                        e.Graphics.DrawRectangle(pen, bounds.X, bounds.Y, bounds.Width - 1, bounds.Height - 1);
                    }
                }
            }
        }
    
    }
    

    You'll have to fill in the // Something... lines and do some kind of drawing that makes it obvious to the user that the button is pressed or selected. Maybe draw a rectangle with a thick Pen, it is up to you.