C#MenuStrip Panel视觉异常

时间:2017-02-14 16:26:37

标签: c# winforms menuitem menustrip

我正在为一个menustrip着色以匹配我的应用主题。但是,每次尝试时,我都会在面板分隔符左侧看到这种奇怪的视觉异常(白色矩形)。还有一些奇怪的复选框定位(可能相关?)。

造成这种情况的原因是什么,如何将其删除?

谢谢

Menu Strip Issue

enter image description here

示例代码:

private Color MainColor = Color.FromArgb(39, 40, 34);

public class MenuStripRenderer : ToolStripProfessionalRenderer
{
    protected override void OnRenderMenuItemBackground(ToolStripItemRenderEventArgs e)
    {
        Rectangle rect = new Rectangle(Point.Empty, e.Item.Size);

        if (e.Item.Selected)
        {
            Color color = Color.FromArgb(24, 25, 19);
            using (SolidBrush brush = new SolidBrush(color))
                e.Graphics.FillRectangle(brush, rect);
        }
        else
        {
            using (SolidBrush brush = new SolidBrush(MainColor))
                e.Graphics.FillRectangle(brush, rect);
        }
    }

    protected override void OnRenderItemText(ToolStripItemTextRenderEventArgs e)
    {
        e.Item.ForeColor = Color.White;
        base.OnRenderItemText(e);
    }

    protected override void OnRenderSeparator(ToolStripSeparatorRenderEventArgs e)
    {
        base.OnRenderSeparator(e);
    }

    public MenuStripRenderer() : base(new MenuStripColors()) { }
}

public class MenuStripColors : ProfessionalColorTable
{
    public override Color ToolStripDropDownBackground
    {
        get { return MainColor; }
    }

    public override Color ToolStripContentPanelGradientBegin
    {
        get { return MainColor; }
    }

    public override Color ToolStripContentPanelGradientEnd
    {
        get { return MainColor; }
    }

    public override Color MenuItemSelected
    {
        get { return MainColor; }
    }

    public override Color MenuItemBorder
    {
        get { return MainColor; }
    }

    public override Color MenuItemSelectedGradientBegin
    {
        get { return MainColor; }
    }

    public override Color MenuItemSelectedGradientEnd
    {
        get { return MainColor; }
    }

    public override Color MenuBorder
    {
        get { return MainColor; }
    }
}

// In the forms Load()
this.menuStrip1.Renderer = new MenuStripRenderer();
this.menuStrip1.BackColor = MainColor;
this.menuStrip1.ForeColor = Color.White;

1 个答案:

答案 0 :(得分:2)

我相信你也必须覆盖ImageMargin绘图:

protected override void OnRenderImageMargin(ToolStripRenderEventArgs e) {
  //base.OnRenderImageMargin(e);
  using (SolidBrush brush = new SolidBrush(MainColor)) {
    e.Graphics.FillRectangle(brush, e.AffectedBounds);
  }
}

我不知道是什么导致了您的复选标记问题,因为我无法在我的计算机上复制该问题。我猜也许这是你窗户上的图形DPI设置。