各位牛人,我需要将winform中多个richtextbox、textbox、datagridview做成四个圆角样式,将groupbox做成只有右上角圆角,上面和右面有线条的样式,请问该怎么做呢?C#
正好近期在做类似的项目,可供参考哈
创建一个继承自TextBox、DataGridView、GroupBox等控件类的子类,并重写其Paint事件。在该事件中,使用GraphicsPath对象绘制具有圆角边框的路径。
使用同样继承自Control的子类,重写其OnResize、OnCreateControl这两个方法,调整圆角绘制路径的大小和位置。
以下是一个继承自TextBox的圆角控件的样例代码:
using System.Drawing;
using System.Windows.Forms;
public class RoundTextBox : TextBox
{
public RoundTextBox()
{
SetStyle(ControlStyles.UserPaint | ControlStyles.ResizeRedraw | ControlStyles.SupportsTransparentBackColor, true);
BackColor = Color.Transparent;
Font = new Font("Arial", 10);
}
protected override void OnResize(EventArgs e)
{
base.OnResize(e);
Invalidate();
}
protected override void OnCreateControl()
{
base.OnCreateControl();
Height = 25;
}
protected override void OnPaint(PaintEventArgs e)
{
e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
Rectangle rectBorder = new Rectangle(0, 0, Width - 1, Height - 1);
// 边框的宽度
int borderWidth = 2;
// 圆角半径
int cornerRadius = 6;
GraphicsPath borderPath = DrawRoundRect(rectBorder, cornerRadius, borderWidth, true, true, false, false);
Brush backColorBrush = new SolidBrush(BackColor);
e.Graphics.FillPath(backColorBrush, borderPath);
var borderPen = new Pen(Color.FromArgb(255, 170, 170, 170), borderWidth);
e.Graphics.DrawPath(borderPen, borderPath);
// 在文本框中绘制文本
base.OnPaint(e);
}
private static GraphicsPath DrawRoundRect(Rectangle rect, int radius, int borderWidth, bool leftTopCorner, bool rightTopCorner, bool rightBottomCorner, bool leftBottomCorner)
{
GraphicsPath path = new GraphicsPath();
int x = rect.X;
int y = rect.Y;
int width = rect.Width;
int height = rect.Height;
int d = radius + radius;
if (leftTopCorner)
{
path.AddArc(x, y, d, d, 180, 90);
path.AddLine(x + radius, y, x + width - radius, y);
}
else
{
path.AddLine(x, y, x + width - radius, y);
}
if (rightTopCorner)
{
path.AddArc(x + width - d, y, d, d, 270, 90);
path.AddLine(x + width, y + radius, x + width, y + height - radius);
}
else
{
path.AddLine(x + width, y, x + width, y + height - radius);
}
if (rightBottomCorner)
{
path.AddArc(x + width - d, y + height - d, d, d, 0, 90);
path.AddLine(x + width - radius, y + height, x + radius, y + height);
}
else
{
path.AddLine(x + width, y + height, x + radius, y + height);
}
if (leftBottomCorner)
{
path.AddArc(x, y + height - d, d, d, 90, 90);
path.AddLine(x, y + height - radius, x, y + radius);
}
else
{
path.AddLine(x, y + height, x, y + radius);
}
path.CloseFigure();
return path;
}
}
要绘制只有右上角圆角的GroupBox,可以根据需要继承GroupBox并使用相似的方式进行绘制。