Why does ToolStripMenuItem OnPaint draws only the first item?

chris harper 96 Reputation points

I'm trying to add white space within the item's text in a ContextMenu for that the string after the space is always left aligned and always stands under each other in each item.

What I'm trying to do in the following code:

  • I add the items to the ContextMenu and wants to make it invisible by the foreground and the selection foreground color.
  • I split the string in the XToolStripMenuItem class, calculate the width of the first string and add the padding to the 2nd string.

Problem: The OnPaint gets the 3 items but only draws the first item. I can't see why.

Showing Context menu:

    private void sfButton1_Click(object sender, EventArgs e)
        XContextMenuStrip cms = new XContextMenuStrip();
        cms.ForeColor = cms.BackColor; // Todo later: change foreground selection color for that the text is invisible

        var item1 = new XToolStripMenuItem();
        var item2 = new XToolStripMenuItem();
        var item3 = new XToolStripMenuItem();
        item1.Text = "Test1, padded text";

        item2.Text = "Test2, padded text";
        item3.Text = "Test3, padded text";

        cms.Show(sfButton1, sfButton1.Location);// Todo later: Doesn't work properly (Not at button position)

ContextMenuStrip class inheritance:

internal class XContextMenuStrip : ContextMenuStrip
    public XContextMenuStrip() 
        this.AutoSize = false;
        this.Width = 301;
        this.Height = 300; // Todo later          

ToolStripMenuItem inheritance:

class XToolStripMenuItem : ToolStripMenuItem
    public XToolStripMenuItem() {
        this.AutoSize = false;
        this.Width = 300;

    private static int count;
    protected override void OnPaint(PaintEventArgs e)

        Font font = new Font("Segoe UI", this.Font.Size);
        SolidBrush brush = new SolidBrush(Color.IndianRed);//Todo later: logic for adding the white space between the splitted Text from "this.Text" by DrawString

                              this.Bounds.X + 34.4f, 

        e.Graphics.DrawString("padded Text",
                             this.Bounds.X + 195.4f,
                             this.Bounds.Y, null);


Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,814 questions
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,164 questions
0 comments No comments
{count} votes

0 additional answers

Sort by: Most helpful