问题描述
我想创建一个带有圆角和渐变颜色的自定义组合框.我通过覆盖OnPaint
方法在Button
中实现了相同的功能.但是它不适用于ComboBox
.任何帮助将不胜感激.
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.
我用于覆盖OnPaint
的代码如下:
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;
}
推荐答案
我能够找到此问题的解决方案.实际上,问题在于OnPaint事件没有被Combobox调用.因此,我必须进行以下更改.
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);
}
我必须在构造函数内部调用SetStyle()方法,以便调用OnPaint()事件.
I had to call SetStyle() method inside the constructor so that OnPaint() event will get called.
我发现这篇文章很有趣:从不调用OnPaint覆盖
I found this post as helful : OnPaint override is never called
相同的解决方案可用于自定义文本框.
The same solution can be used for Custom TextBoxes.
这篇关于在Windows窗体中创建带有圆角的自定义ComboBox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!