开发者

Customize ToolStripMenuItem

I want to customize ToolStripMenuItem by overriding OnPaint function. This is a MyToolStripMenuItem:

public class MyToolStripMenuItem : ToolStripMenuItem
{
    public MyToolStripMenuItem()
        :base()
    {
    }

    public MyToolStripMenuItem(string t)
开发者_开发百科        :base(t)
    {
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        Graphics g = e.Graphics;
        Rectangle r = this.Bounds;
        g.FillRectangle(Brushes.Blue, r);
        g.DrawString(this.Text, this.Font, Brushes.Red, r);
    }
}

In my code, I will fill a blue color in item's bound. Now, I will create a list of items on menustrip:

MyToolStripMenuItem1

|___MyToolStripMenuItem2

|___MyToolStripMenuItem3

I don't know why MyToolStripMenuItem3 don't have a blue background.

This is my source code:

http://www.mediafire.com/?2qhmjzzfzzn

Please help me. Thanks.


It's not the way it is done with a ToolStripMenuItem. You give the MenuStrip a custom renderer. For example:

For example:

public partial class Form1 : Form {
    public Form1() {
        InitializeComponent();
        menuStrip1.Renderer = new MyRenderer();
    }
    private class MyRenderer : ToolStripProfessionalRenderer {
        protected override void OnRenderMenuItemBackground(ToolStripItemRenderEventArgs e) {
            if (!e.Item.Selected) base.OnRenderMenuItemBackground(e);
            else {
                Rectangle rc = new Rectangle(Point.Empty, e.Item.Size);
                e.Graphics.FillRectangle(Brushes.Beige, rc);
                e.Graphics.DrawRectangle(Pens.Black, 1, 0, rc.Width - 2, rc.Height - 1);
            }
        }
    }
}


The problem with using OnRenderMenuItemBackground() is that it applies to the whole menu and not just the one ToolStripMenuItem.

The error in the code lies in Rectangle r = this.Bounds; which produces the wrong area. Change this to Rectangle r = e.ClipRectangle and it should work ok. (For some reason the Bounds has the wrong Y component).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜