I want to create a custom combo-box with rounded corners and gradient color. I have implemented the same feature in Button
by overriding the OnPaint
method. But it is not working for ComboBox
. Any help will be appreciated.
The code I am using for overriding OnPaint
is given below:
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;
}
I was able to find a solution to this problem. Actually, the problem was that OnPaint event was not getting called for Combobox. So I had to do the following changes.
public CustomComboBox()
{
InitializeComponent();
SetStyle(ControlStyles.UserPaint, true);
}
I had to call SetStyle() method inside the constructor so that OnPaint() event will get called.
I found this post as helful : OnPaint override is never called
The same solution can be used for Custom TextBoxes.