简体   繁体   English

在 toolStripMenuItem 周围绘制一个矩形

[英]Drawing a rectangle around a toolStripMenuItem

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.但我无法弄清楚如何使用 toolStripMenuItem 执行此操作,以便我可以在它周围绘制一个矩形。

Any help is appreciated.任何帮助表示赞赏。 Thanks!谢谢!

The easiest way is to inherit from the control and override the OnPaint method, then change all instances of ToolStripMenuItem to MyToolStripMenuItem .最简单的方法是从控件继承并覆盖OnPaint方法,然后将ToolStripMenuItem所有实例更改为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.稍微复杂一点,但从长远来看可维护性更好,是实现自定义ToolStripRenderer ,它允许您更改整个事物的外观,例如使其看起来像 VS2010。

在此处输入图片说明

(Image taken from VBForums ) (图片取自VBForums

You can try using the Paint event (you should rarely ever use CreateGraphics) and the ContentRectangle property:您可以尝试使用 Paint 事件(您应该很少使用 CreateGraphics)和 ContentRectangle 属性:

void toolStripButton1_Paint(object sender, PaintEventArgs e) {
  e.Graphics.DrawRectangle(Pens.Red, toolStripButton1.ContentRectangle);
}

While ToolStripMenuItem is not a control, its parent is.虽然ToolStripMenuItem不是控件,但它的父项是。 Therefore you can call因此你可以打电话

myToolStripMenuItem.GetCurrentParent().CreateGraphics()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM