1

我想创建一个带有圆角和渐变颜色的自定义组合框。我Button通过覆盖该OnPaint方法实现了相同的功能。但它不适用于ComboBox. 任何帮助将不胜感激。

我用于覆盖的代码OnPaint如下:

protected override void OnPaint(PaintEventArgs paintEvent)
{
     Graphics graphics = paintEvent.Graphics;

     SolidBrush backgroundBrush = new SolidBrush(this.BackColor);
     graphics.FillRectangle(backgroundBrush, ClientRectangle);

     graphics.SmoothingMode = SmoothingMode.AntiAlias;

     Rectangle rectangle = new Rectangle(ClientRectangle.X, ClientRectangle.Y, ClientRectangle.Width - 1, ClientRectangle.Height - 1);
     GraphicsPath graphicsPath = RoundedRectangle(rectangle, cornerRadius, 0);
     Brush brush = new LinearGradientBrush(rectangle, gradientTop, gradientBottom, LinearGradientMode.Horizontal);
     graphics.FillPath(brush, graphicsPath);

     rectangle = new Rectangle(ClientRectangle.X, ClientRectangle.Y, ClientRectangle.Width - 1, ClientRectangle.Height - 100);
     graphicsPath = RoundedRectangle(rectangle, cornerRadius, 2);
     brush = new LinearGradientBrush(rectangle, gradientTop, gradientBottom, LinearGradientMode.Horizontal);
     graphics.FillPath(brush, graphicsPath);
}

private GraphicsPath RoundedRectangle(Rectangle rectangle, int cornerRadius, int margin)
{
    GraphicsPath roundedRectangle = new GraphicsPath();
    roundedRectangle.AddArc(rectangle.X + margin, rectangle.Y + margin, cornerRadius * 2, cornerRadius * 2, 180, 90);
    roundedRectangle.AddArc(rectangle.X + rectangle.Width - margin - cornerRadius * 2, rectangle.Y + margin, cornerRadius * 2, cornerRadius * 2, 270, 90);
    roundedRectangle.AddArc(rectangle.X + rectangle.Width - margin - cornerRadius * 2, rectangle.Y + rectangle.Height - margin - cornerRadius * 2, cornerRadius * 2, cornerRadius * 2, 0, 90);
    roundedRectangle.AddArc(rectangle.X + margin, rectangle.Y + rectangle.Height - margin - cornerRadius * 2, cornerRadius * 2, cornerRadius * 2, 90, 90);
    roundedRectangle.CloseFigure();
    return roundedRectangle;
}
4

1 回答 1

5

我能够找到解决这个问题的方法。实际上,问题在于 Combobox 没有调用 OnPaint 事件。所以我不得不做以下改变。

public CustomComboBox()
{
    InitializeComponent();
    SetStyle(ControlStyles.UserPaint, true);
}

我必须在构造函数中调用 SetStyle() 方法,以便调用 OnPaint() 事件。

我发现这篇文章很有帮助:OnPaint override is never called

相同的解决方案可用于自定义文本框。

于 2013-07-23T05:20:40.417 回答