C# Winform中TableLayoutPanel高亮区域边框偏移及颜色匹配实现问题
TableLayoutPanel高亮自定义边框实现方案
核心改动点
- 偏移实现:通过类级别
Padding参数统一控制边框偏移量,支持内外偏移调整,逻辑可复用 - 颜色匹配:优先使用系统原生
SystemColors.ControlDark颜色,和PictureBox的Fixed边框完全一致,适配系统主题切换,也可保留自定义取色值Color.FromArgb(100,100,100) - 资源优化:
Pen对象使用using语句自动释放,避免GDI资源泄漏 - 逻辑补全:补充底部边框绘制逻辑,实现完整外围边框效果
完整实现代码
// 自定义边框偏移量,正数值为向内偏移,负数值为向外偏移 private readonly Padding _borderOffset = new Padding(2); // 边框颜色,和系统PictureBox Fixed边框完全匹配 private readonly Color _borderColor = SystemColors.ControlDark; // 边框宽度 private const int _borderThickness = 2; private void tlp1_CellPaint(object sender, TableLayoutCellPaintEventArgs e) { if (!confirmedView) return; using (Pen borderPen = new Pen(_borderColor, _borderThickness)) { // 绘制顶部边框:起始行,覆盖3列宽度 if (e.Row == cellStartRowIndex && e.Column is >= cellStartColumnIndex and <= cellStartColumnIndex + 2) { var startPoint = new Point(e.CellBounds.Left + _borderOffset.Left, e.CellBounds.Top + _borderOffset.Top); var endPoint = new Point(e.CellBounds.Right - _borderOffset.Right, e.CellBounds.Top + _borderOffset.Top); e.Graphics.DrawLine(borderPen, startPoint, endPoint); } // 绘制底部边框:起始行+1,覆盖3列宽度 if (e.Row == cellStartRowIndex + 1 && e.Column is >= cellStartColumnIndex and <= cellStartColumnIndex + 2) { var startPoint = new Point(e.CellBounds.Left + _borderOffset.Left, e.CellBounds.Bottom - _borderOffset.Bottom); var endPoint = new Point(e.CellBounds.Right - _borderOffset.Right, e.CellBounds.Bottom - _borderOffset.Bottom); e.Graphics.DrawLine(borderPen, startPoint, endPoint); } // 绘制左侧边框:起始列,覆盖2行高度 if (e.Column == cellStartColumnIndex && e.Row is >= cellStartRowIndex and <= cellStartRowIndex + 1) { var startPoint = new Point(e.CellBounds.Left + _borderOffset.Left, e.CellBounds.Top + _borderOffset.Top); var endPoint = new Point(e.CellBounds.Left + _borderOffset.Left, e.CellBounds.Bottom - _borderOffset.Bottom); e.Graphics.DrawLine(borderPen, startPoint, endPoint); } // 绘制右侧边框:起始列+3,覆盖2行高度 if (e.Column == cellStartColumnIndex + 3 && e.Row is >= cellStartRowIndex and <= cellStartRowIndex + 1) { var startPoint = new Point(e.CellBounds.Right - _borderOffset.Right, e.CellBounds.Top + _borderOffset.Top); var endPoint = new Point(e.CellBounds.Right - _borderOffset.Right, e.CellBounds.Bottom - _borderOffset.Bottom); e.Graphics.DrawLine(borderPen, startPoint, endPoint); } } }
调整
_borderOffset的参数值即可修改偏移幅度,数值越大边框越靠近单元格中心。
内容的提问来源于stack exchange,提问作者Gokhan
相关产品推荐
相关产品推荐

