我想创建一个带有圆角和渐变颜色的自定义组合框。我通过覆盖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;
}
最佳答案
我能够找到解决该问题的方法。实际上,问题在于OnPaint事件没有被Combobox调用。因此,我必须进行以下更改。
public CustomComboBox()
{
InitializeComponent();
SetStyle(ControlStyles.UserPaint, true);
}
我必须在构造函数内部调用SetStyle()方法,以便调用OnPaint()事件。
我发现这篇文章非常有帮助:OnPaint override is never called
相同的解决方案可以用于自定义文本框。
关于c# - 在Windows窗体中创建带有圆角的自定义ComboBox,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17784909/