Create custom ComboBox with rounded corners in Windows Forms

与世无争的帅哥 提交于 2019-12-09 23:35:57

问题


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;
}

回答1:


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.



来源:https://stackoverflow.com/questions/17784909/create-custom-combobox-with-rounded-corners-in-windows-forms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!