views:

75

answers:

2

I am creating a .NET form application in Visual Studio 9. In the designer I have added a MenuStrip to where I have added ToolStripMenuItems (standard dropdown menu). To the ToolStripMenuItems I have added images by setting the Image property.

The images appear as expected, except they are aligned to the left, even though the ImageAlign propery is set to MiddleCenter. Changing the ImageAlign to any value does not seem to have any effect on the alignment of the image.

What I want is to have the image aligned in the middle of the "image column" on the left side of the drop down menu. Is the ImageAlign property not supposed to do this?

+1  A: 

I've run into this before. The ImageAlign, TextAlign and TextImageRelation properties don't seem to do anything on these controls. I ended up having to remake all the images the same size, centered in the background how I wanted them to look.

Shawn Steward
I thought about the same solution, but was hoping there would be a programmatic solution to the problem.
Oberon
A: 

This code sorta works:

public partial class Form1 : Form {
    public Form1() {
        InitializeComponent();
        menuStrip1.Renderer = new MyRenderer();
    }
    private class MyRenderer : ToolStripProfessionalRenderer {
        protected override void OnRenderItemImage(ToolStripItemImageRenderEventArgs e) {
            Console.WriteLine("{0}: {1} <= {2}", e.Item.Name, e.ImageRectangle, e.Image.Size);
            if (e.Item is ToolStripMenuItem) {
                int x = e.ImageRectangle.Left + 20 - e.Image.Width;
                e.Graphics.DrawImage(e.Image, new Point(x, 0));
            }
            else base.OnRenderItemImage(e);
        }
    }
}

The ultimate problem is that the layout of the menu item is calculated and internal. You can't find out where the image ends and the text starts. The OnRenderItemImage() is sadly called without any hint how wide the image area is. Bit of a design goof there.

Hans Passant
@nobugz, your solution works for me, thanks. Though not as easy as if the ImageAlign property would work as I expected.
Oberon
@oberon, yes, you'll encounter this a lot when trying to customize the ToolStrip classes. They have some design flaws and shipped before they were really done. Please close your thread by marking it answered.
Hans Passant