Windows 10 Styled ContextMenuStrip

2019-01-23 20:54发布

Is there a way to create ContextMenuStrip using Visual Studio and Forms with Windows 10 style. I know, that its Renderer can be changed in order to have look like Windows Vista, 7 and 8. And that is what I made:

enter image description here

But I also would like to make it look like this in Windows 10:

enter image description here

Is there a way to do it using Windows Forms, or it should be done in some special way, using Metro classes etc?

1条回答
劳资没心,怎么记你
2楼-- · 2019-01-23 21:10

You can implement your custom Renderer and override OnRenderArrow and OnRenderItemCheck and pass your custom ColorTable to it. Then set it as Renderer of your ContextMenu.

enter image description here

Code for ColorTable:

public class MyColorTable : ProfessionalColorTable
{
    public override Color MenuItemBorder
    {
        get { return Color.WhiteSmoke; }
    }
    public override Color MenuItemSelected
    {
        get { return Color.WhiteSmoke; }
    }
    public override Color ToolStripDropDownBackground
    {
        get { return Color.White; }
    }
    public override Color ImageMarginGradientBegin
    {
        get { return Color.White; }
    }
    public override Color ImageMarginGradientMiddle
    {
        get { return Color.White; }
    }
    public override Color ImageMarginGradientEnd
    {
        get { return Color.White; }
    }
}

Code for Renderer:

public class MyRenderer : ToolStripProfessionalRenderer
{
    public MyRenderer()
        : base(new MyColorTable())
    {
    }
    protected override void OnRenderArrow(ToolStripArrowRenderEventArgs e)
    {
        e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
        var r = new Rectangle(e.ArrowRectangle.Location, e.ArrowRectangle.Size);
        r.Inflate(-2, -6);
        e.Graphics.DrawLines(Pens.Black, new Point[]{
        new Point(r.Left, r.Top),
        new Point(r.Right, r.Top + r.Height /2), 
        new Point(r.Left, r.Top+ r.Height)});
    }

    protected override void OnRenderItemCheck(ToolStripItemImageRenderEventArgs e)
    {
        e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
        var r = new Rectangle(e.ImageRectangle.Location, e.ImageRectangle.Size);
        r.Inflate(-4, -6);
        e.Graphics.DrawLines(Pens.Black, new Point[]{
        new Point(r.Left, r.Bottom - r.Height /2),
        new Point(r.Left + r.Width /3,  r.Bottom), 
        new Point(r.Right, r.Top)});
    }
}

Code for Form Load:

private void Form_Load(object sender, EventArgs e)
{
    this.contextMenuStrip1.Renderer = new MyRenderer();
}
查看更多
登录 后发表回答