Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ToolStripMenuItem bigger vertical padding, or vertically centering text in a bigger ToolStripMenuItem

I'm trying to set a bigger vertical padding for ToolStripMenuItems in a ContextMenuStrip. However, changing the Padding.Top property adds padding to the bottom, instead of the top.

I also tried setting a larger Height for the ToolStripMenuItem, it works, however, the text always gets aligned on top, even if the TextAlign property is MiddleCenter. It should be vertical aligned to the center!

I've tried different settings for different properties, nothing works. The idea is that I cannot get the ToolStripMenuItem to have more space around its text, both to the top and to the bottom.

I'm using C#, Windows Forms, Net 2.0, Visual Studio 2010 Express, Windows 7.

like image 473
Alex Vang Avatar asked Jun 01 '11 17:06

Alex Vang


3 Answers

You can get the same effect using Margin instead of Padding which will keep the Text of the ToolStripMenuItem aligned.

The drawback is that this wont modify the size of the highlight rectangle when the item is selected so it can look a little strange if you increase a lot the height.

like image 100
InBetween Avatar answered Oct 29 '22 13:10

InBetween


In addition to InBetween's answer, you can fix the highlight rectangle by using a custom renderer and adjusting its "TextRectangle" property. Here's some sample code:

    var itemHeight = 36;
    var verticalPadding = 36 - TextRenderer.MeasureText("A", _DisplayNameFont).Height) / 2;
    menu.Renderer = new MyRenderer { VerticalPadding = verticalPadding };

    class MyRenderer : ToolStripSystemRenderer
    {
        public int VerticalPadding { get; set; }

        protected override void OnRenderItemText(ToolStripItemTextRenderEventArgs e)
        {
            if (null == e)
            { return; }
            e.TextFormat &= ~TextFormatFlags.HidePrefix;
            e.TextFormat |= TextFormatFlags.VerticalCenter;
            var rect = e.TextRectangle;
            rect.Offset(0, VerticalPadding);
            e.TextRectangle = rect;
            base.OnRenderItemText(e);
        }
    }
like image 22
computerGuyCJ Avatar answered Oct 29 '22 14:10

computerGuyCJ


Adding a new line does the job.

It's not the best solution, but it's a quick way to add some padding.

Works well when adding support for small touch screens.

this.configToolStripMenuItem.Text = "\r\nSettings";
like image 45
Joel Davis Avatar answered Oct 29 '22 13:10

Joel Davis