永远不会为从Button派生的控件调用OnPaintBackground方法

我已经制作了一个GradientButton类,它假设是一个充满渐变背景的Button。

我在OnPaintBackground()方法中绘制渐变填充。 不幸的是,它永远不会被调用,当然我通过工具箱向Form添加了一个GradientButton

  public class GradientButton : Button { public Color Color1 { get; set; } public Color Color2 { get; set; } public float Angle { get; set; } public GradientButton() { Color1 = Color.YellowGreen; Color2 = Color.LightGreen; Angle = 30; } protected override void OnPaintBackground(PaintEventArgs e) { base.OnPaintBackground(e); Debug.WriteLine("This never prints"); using (LinearGradientBrush brush = new LinearGradientBrush(this.ClientRectangle, Color1, Color2, Angle)) { e.Graphics.FillRectangle(brush, this.ClientRectangle); } } protected override void OnResize(EventArgs e) { base.OnResize(e); Invalidate(); } } 

问题:如何用渐变填充按钮的背景? 为什么不调用OnPaintBackground ? 据我所知,它应该被称为onPaint方法。

这是因为Button类设置了ControlStyles.Opaque标志,根据文档说明:

如果为true,则控件被绘制为不透明且背景未绘制。

您可以在类构造函数中将其关闭

 SetStyle(ControlStyles.Opaque, false); 

并将调用您的OnPaintBackground覆盖。

然而,它没有多大帮助 – 有一个原因要将标志设置为trueOnPaint绘制按钮的背景和面,因此无论你在OnPaintBackground做什么都不会对按钮外观产生任何影响。 不幸的是,没有选择只绘制背景,所以你需要覆盖OnPaint并实际绘制所有内容

你需要在构造函数中设置表单的样式……

 this.SetStyle(ControlStyles.UserPaint, true); 

确保重写OnPaint方法。 您可以组合ControlStyle的许多设置

我会这样做。

首先,将构造函数更改为:

  public GradientButton() { Color1 = Color.YellowGreen; Color2 = Color.LightGreen; Angle = 30; Paint += new PaintEventHandler(GradientButton_Paint); } 

然后添加以下过程:

  private void GradientButton_Paint(object sender,PaintEventArgs e) { Debug.WriteLine("This never prints"); using (LinearGradientBrush brush = new LinearGradientBrush(this.ClientRectangle,Color1,Color2,Angle)) { e.Graphics.FillRectangle(brush, this.ClientRectangle); } } 

我不完全确定为什么你的代码不起作用,但我描述的方式总是对我有用。 希望这足够好。