我想做同样的事情来制作一个上下文菜单标题,我可以在其中设置工具条菜单项的背景、前景和边框颜色。
它与其他答案相似,但更加独立。
它看起来如何
代码是如何实现的;
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;//= new Font("Segoe UI", 10, FontStyle.Bold, System.Drawing.GraphicsUnit.Point, 1, false)
public ToolStripHeader(string text, Font font, Color textcolor, Color BackgroundColor, Color BorderColor) //: base(new Label())
{
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;//= new Font("Segoe UI", 10, FontStyle.Bold, System.Drawing.GraphicsUnit.Point, 1, false)
public HeaderRenderer(Font font, Color textcolor, Color BackgroundColor, Color BorderColor) //: base(new Label())
{
_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
{
//Example
//Rectangle rc = new Rectangle(Point.Empty, e.Item.Size);
//e.Graphics.FillRectangle(Brushes.DarkGray, rc);
//e.Graphics.DrawRectangle(Pens.Black, 1, 0, rc.Width - 2, rc.Height - 1);
}
}
protected override void OnRenderItemText(ToolStripItemTextRenderEventArgs e)
{
if (e.Item.GetType() == typeof(ToolStripHeader))
{
e.TextColor = _FontColor;
e.TextFont = _Font;
}
base.OnRenderItemText(e);
}
}
}