2010-02-19 31 views
0

我正在使用ButtonRenderer在自定义单元格中绘制按钮。我想按钮有一个非标准的BackColor。这由普通按钮支持,但按钮单元格或ButtonRenderer中没有任何内容支持它。如何绘制带有非标准BackColor的按钮?该方法必须考虑用户的主题 - 我不能只绘制我自己的按钮。如何绘制带有非标准BackColor的按钮?

回答

2

ButtonRenderer使用VisualStyleRenderer.DrawBackground()绘制按钮背景。该方法非常了解用户选择的主题,按钮的背景将使用主题指定的颜色。使用非标准的BackColor会违反用户选择的主题。你不能两面都有。

Button类实际上并不使用ButtonRenderer,它使用从System.Windows.Forms.ButtonInternal命名空间的内部ButtonBaseAdapter类派生的三个渲染器之一。这些渲染器是内部的,你不能在你自己的代码中使用它们。用Reflector或Reference Source看看它们的含义。专注于PaintButtonBackground方法。

+0

这是ButtonStandardAdapter.PaintThemedButtonBackground发现竟然是至关重要的一个美化按钮的外观 - 它调用ButtonRender.DrawButton,然后收缩了4PX矩形,无论的主题。 – Simon 2010-02-19 13:49:56

-1

使用提供的ControlPaint和TextRenderer类绘制自己的按钮。这相当简单。我把这些代码快速地放在一起给你看。您可以通过设置边框样式等

private ButtonState state = ButtonState.Normal; 
    public ButtonCell(): base() 
    { 
     this.Size = new Size(100, 40); 
     this.Location = new Point(50, 50); 
     this.Font = SystemFonts.IconTitleFont; 
     this.Text = "Click here";  
    } 
    private void DrawFocus() 
    { 
     Graphics g = Graphics.FromHwnd(this.Handle); 
     Rectangle r = Rectangle.Inflate(this.ClientRectangle, -4, -4); 
     ControlPaint.DrawFocusRectangle(g, r); 
     g.Dispose(); 
    } 
    private void DrawFocus(Graphics g) 
    { 
     Rectangle r = Rectangle.Inflate(this.ClientRectangle, -4, -4); 
     ControlPaint.DrawFocusRectangle(g, r); 
    } 
    protected override void OnPaint(PaintEventArgs e) 
    { 
     base.OnPaint(e); 
     if (state == ButtonState.Pushed) 
      ControlPaint.DrawBorder3D(e.Graphics, e.ClipRectangle, Border3DStyle.Sunken); 
     else 
      ControlPaint.DrawBorder3D(e.Graphics, e.ClipRectangle, Border3DStyle.Raised); 
     TextRenderer.DrawText(e.Graphics, Text, this.Font, e.ClipRectangle, this.ForeColor, 
      TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter); 
    } 
    protected override void OnGotFocus(EventArgs e) 
    { 
     DrawFocus(); 
     base.OnGotFocus(e); 
    } 
    protected override void OnLostFocus(EventArgs e) 
    { 
     Invalidate(); 
     base.OnLostFocus(e); 
    } 
    protected override void OnMouseEnter(EventArgs e) 
    { 
     DrawFocus(); 
     base.OnMouseEnter(e); 
    } 

    protected override void OnMouseLeave(EventArgs e) 
    { 
     Invalidate(); 
     base.OnMouseLeave(e); 
    } 
    protected override void OnMouseDown(MouseEventArgs e) 
    { 
     state = ButtonState.Pushed; 
     Invalidate(); 
     base.OnMouseDown(e); 
    } 
    protected override void OnMouseUp(MouseEventArgs e) 
    { 
     state = ButtonState.Normal; 
     Invalidate(); 
     base.OnMouseUp(e); 
    } 
+0

ControlPaint绘制了一个毫无意义的按钮 - 正如我在问题中所说的,我必须考虑用户的主题 - 我不能只绘制我自己的按钮。 – Simon 2010-02-19 15:35:11

+0

对不起,我错过了。从上面的帖子你似乎发现为什么它不允许背景重绘,但你有没有找到一个解决方案?也有兴趣从中学习。 – 2010-02-20 11:17:49

+0

是的 - 正如nobugz所建议的那样,我使用反射器来看Button是如何做到的。 – Simon 2010-02-22 09:12:32

相关问题