1

I know that I can draw rectangles just about anywhere I want using

using (Graphics G = myControl.CreateGraphics())
{
    G.DrawRectangle(new Pen(myColor),myControl.Bounds);
}

but I'm having trouble figuring out how to do this with a toolStripMenuItem, so that I can draw a rectangle around it.

Any help is appreciated. Thanks!

user2320861
  • 1,391
  • 2
  • 11
  • 28

3 Answers3

1

The easiest way is to inherit from the control and override the OnPaint method, then change all instances of ToolStripMenuItem to MyToolStripMenuItem.

class MyToolStripMenuItem : ToolStripMenuItem
{
    protected override void OnPaint( PaintEventargs pe )
    {
        base.OnPaint( pe );

        pe.ClipRectangle.Inflate( -1, -1 );
        pe.Graphics.DrawRectangle( Pens.Black, pe.ClipRectangle );
    }
}

A bit more complicated, but better in the long run for maintainability, is implementing a custom ToolStripRenderer which would allow you to change the look of the entire thing, for example making it look like VS2010.

enter image description here

(Image taken from VBForums)

  • I like this solution for greater customization of the toolstripmenuitem! However, I only want to paint the rectangle sometimes, so subclassing isn't necessary for me. Thanks for the thorough answer! – user2320861 Mar 18 '14 at 18:15
0

You can try using the Paint event (you should rarely ever use CreateGraphics) and the ContentRectangle property:

void toolStripButton1_Paint(object sender, PaintEventArgs e) {
  e.Graphics.DrawRectangle(Pens.Red, toolStripButton1.ContentRectangle);
}
LarsTech
  • 80,625
  • 14
  • 153
  • 225
  • This is more what I was looking for. I created a generic paint method to which I can attach and detach at will the `Paint` event of my toolstripmenuitems. This way I control which menuitem gets the rectangle without having a separate paint method for each. Thanks! – user2320861 Mar 18 '14 at 18:17
0

While ToolStripMenuItem is not a control, its parent is. Therefore you can call

myToolStripMenuItem.GetCurrentParent().CreateGraphics()
dahall
  • 318
  • 3
  • 6