我想做同样的事情来创建一个contextmenustrip标题,我可以设置toolstripmenuitem的背景、前景和边框颜色。
这与其他答案类似,但更加自包含。
它的外观
代码实现方式如下:
ContextMenustrip.Items.Add(new CustomCMSItems.ToolStripHeader("Shifts", new Font("Segoe UI", 10, FontStyle.Bold, System.Drawing.GraphicsUnit.Point, 1, false), Color.Black, Color.LightGray, Color.Red));
public class ToolStripHeader : ToolStripMenuItem
{
Color _BackColor;
Color _BorderColor;
Color _FontColor;
Font _Font;
public ToolStripHeader(string text, Font font, Color textcolor, Color BackgroundColor, Color BorderColor)
{
this.Padding = Padding.Empty;
_BackColor = BackgroundColor;
_BorderColor = BorderColor;
_FontColor = textcolor;
_Font = font;
this.Text = text;
}
protected override void OnParentChanged(ToolStrip oldParent, ToolStrip newParent)
{
base.OnParentChanged(oldParent, newParent);
if (newParent != null)
{
if (newParent.GetType() == typeof(ContextMenuStrip))
{
newParent.Renderer = new HeaderRenderer(_Font, _FontColor, _BackColor, _BorderColor);
}
}
}
private class HeaderRenderer : ToolStripProfessionalRenderer
{
Color _BackColor;
Color _BorderColor;
Color _FontColor;
Font _Font;
public HeaderRenderer(Font font, Color textcolor, Color BackgroundColor, Color BorderColor)
{
_BackColor = BackgroundColor;
_BorderColor = BorderColor;
_FontColor = textcolor;
_Font = font;
}
protected override void OnRenderMenuItemBackground(ToolStripItemRenderEventArgs e)
{
if (e.Item.GetType() == typeof(ToolStripHeader))
{
Rectangle rc = new Rectangle(Point.Empty, e.Item.Size);
SolidBrush brush = new SolidBrush(_BackColor);
Pen pen = new Pen(_BorderColor);
e.Graphics.FillRectangle(brush, rc);
e.Graphics.DrawRectangle(pen, 1, 0, rc.Width - 2, rc.Height - 1);
return;
}
base.OnRenderMenuItemBackground(e);
if (!e.Item.Selected) base.OnRenderMenuItemBackground(e);
else
{
}
}
protected override void OnRenderItemText(ToolStripItemTextRenderEventArgs e)
{
if (e.Item.GetType() == typeof(ToolStripHeader))
{
e.TextColor = _FontColor;
e.TextFont = _Font;
}
base.OnRenderItemText(e);
}
}
}
menuRefresh
的类型是什么?ToolStripMenuItem
还是其他什么? - Sriram SakthivelmenuStrip.Renderer = new MyRenderer()
?你能否发布一个小而完整的示例来演示问题? - Sriram Sakthivel