在Windows窗体中创建带有圆角的自定义ComboBox

Sre*_*V.S 1 c# combobox onpaint winforms

我想创建一个带有圆角和渐变颜色的自定义组合框。我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;
}
Run Code Online (Sandbox Code Playgroud)

Sre*_*V.S 5

我能够找到解决该问题的方法。实际上,问题在于OnPaint事件没有被Combobox调用。因此,我必须进行以下更改。

public CustomComboBox()
{
    InitializeComponent();
    SetStyle(ControlStyles.UserPaint, true);
}
Run Code Online (Sandbox Code Playgroud)

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

我发现这篇文章非常有帮助:永远不会调用OnPaint覆盖

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

  • 您有机会提供完整的样本吗?我已将功能和线路添加到我的项目中,但无法使其工作。看到一个有效的例子会非常有帮助。 (2认同)