When I'm changing text of a ToolStripLabel
in my context menu, the context menu isn't resized automatically as it's supposed to be, when I change text of a menu item.
Looks like this then:
How can I make the context menu resize properly?
I could change text of a real menu item but I see that as a dirty solution.
Test Form: (use left mouse button, left side and right side)
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);
}
}
}
Yes, ContextMenuStrip doesn't recalculate layout when you assign the Text property of that menu item. Arguably it should do it lazily but that looks borken. You have to help, it is a one-liner:
menuLabel.Text = "hello world hello world hello world";
ContextMenuStrip.PerformLayout();