winform重绘控件边框

首先添加一个用户控件

 

 对于重绘边框有三个需要考虑的东西

1:是否显示边框

2:边框颜色

3:边框宽度

所以定义三个私有变量

/// <summary>
/// 是否显示边框
/// </summary>
private bool _isShowRect = false;
/// <summary>
/// 边框颜色
/// </summary>
private Color _rectColor = Color.FromArgb(220, 220, 220);
/// <summary>
/// 边框宽度
/// </summary>
private float _rectWidth = 2;

 

使用OnPaint事件可以随时绘制图形所以我们需要重写OnPaint事件


protected override void OnPaint(PaintEventArgs e)
{
GraphicsPath graphicsPath = new GraphicsPath();
/////绘制边框
//graphicsPath.AddLine(new Point(0, 0), new Point(base.Width,0));
//graphicsPath.AddLine(new Point(0, 0), new Point(0,base.Height));
////-1的问题是微软控件像素的问题,所以不直接用下面获取控件的方式
//graphicsPath.AddLine(new Point(0, base.Height-1), new Point(base.Width-1, base.Height-1));
//graphicsPath.AddLine(new Point( base.Width-1, base.Height), new Point(base.Width-1,0));
///或者下面-1的方法
Rectangle clientRectangle = base.ClientRectangle;
clientRectangle.Width -= 1;
clientRectangle.Height -= 1;
graphicsPath.AddRectangle(clientRectangle);
if (IsShowRect)
{
Color rectColor = this._rectColor;
Pen pen = new Pen(rectColor,_rectWidth);
e.Graphics.DrawPath(pen, graphicsPath);
}
//调用基类方法
//OnPaint方法引发Paint事件,所以重写OnPaint方法,一定要调用base.OnPaint,否则就不会引发Paint事件了。
base.OnPaint(e);//调用基类方法
}

为什么要-1 画个图给大家就明白了

 

 

 

posted @   黑哥聊dotNet  阅读(1604)  评论(1编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示