ContextMenuStrip does not resize

When I change the text ToolStripLabel

in my context menu, the context menu does not automatically change as it was supposed to be when I change the text of the menu item.
It looks like then:

enter image description here

How can I resize the context menu correctly?
I could change the text of the real menu item, but I see this as a messy solution.


Test form: (use the left mouse button, left and right)

using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1: Form
    {
        private ToolStripLabel menuLabel;

        private void CreateNewContextMenu()
        {
            ContextMenuStrip = new ContextMenuStrip();

            // label
            menuLabel = new ToolStripLabel("hello");
            menuLabel.ForeColor = Color.Blue;
            ContextMenuStrip.Items.Add(menuLabel);

            // items
            ContextMenuStrip.Items.Add("Test");
            ContextMenuStrip.Items.Add("Cut");
            ContextMenuStrip.Items.Add("&Copy");
            ContextMenuStrip.Items.Add("&Paste");
            ContextMenuStrip.Items.Add("&Delete");
        }

        protected override void OnMouseClick(MouseEventArgs e)
        {
            CreateNewContextMenu();
            menuLabel.Text = "hello world hello world hello world";
            Point p = PointToScreen(Point.Empty);

            // left
            if (e.X < ClientSize.Width / 2)
                ContextMenuStrip.Show(p.X + 8, p.Y + 8);
            // right
            else
            {
                ContextMenuStrip.Items[1].Text = menuLabel.Text;
                ContextMenuStrip.Show(p.X + ClientSize.Width - 8, p.Y + 8);
            }

            base.OnMouseClick(e);
        }
    }
}

      

+3


source to share


1 answer


Yes, the ContextMenuStrip does not recalculate the layout when assigning the Text property of this menu item. It should probably do it lazily, but it looks like borken. You should help, this is a one-liner:



    menuLabel.Text = "hello world hello world hello world";
    ContextMenuStrip.PerformLayout();

      

+4


source







All Articles