运行时动态创建的Label控件如何修改其自定义边框颜色?
问题原因
- 现有绘制逻辑绑定的是窗体的
Paint事件,在窗体层绘制的矩形会被上层的Label控件覆盖,无法显示 - 绘制时使用Label在窗体上的坐标计算位置,就算没有被控件覆盖,边框位置也会与Label错位
- Label设置了
BorderStyle = BorderStyle.Fixed3D,自带的3D边框会和自定义边框冲突
修正方案
直接给动态创建的Label绑定自身的Paint事件,在Label的绘制层渲染自定义边框,步骤如下:
- 移除Label自带边框,改为自定义绘制
- 动态创建Label时绑定Paint事件
- 在Paint事件中基于Label自身坐标绘制边框
修正后的完整代码:
Form_Load 事件代码
Public Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim Title As New Label Title.Text = "BROKERS" Title.Font = New Drawing.Font("Times New Roman", 30, FontStyle.Bold) Me.Controls.Add(Title) Title.ForeColor = Color.Red Title.Location = New Point((Me.Width / 2), (Me.Height / 2)) Title.BackColor = Color.Black Title.Size = New System.Drawing.Size(220, 50) Title.BringToFront() ' 关闭自带边框 Title.BorderStyle = BorderStyle.None ' 绑定Label自身的Paint事件 AddHandler Title.Paint, AddressOf Label_CustomPaint Me.Size = New System.Drawing.Size(900, 700) End Sub
自定义边框绘制事件代码
Private Sub Label_CustomPaint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Dim targetLabel As Label = CType(sender, Label) ' 矩形宽高各减1,避免边框边缘超出控件显示区域被截断 Dim borderRect As New Rectangle(0, 0, targetLabel.Width - 1, targetLabel.Height - 1) ' Using语句会自动释放Pen资源,无需手动调用Dispose Using borderPen As New Pen(Color.Red, 4.0) e.Graphics.DrawRectangle(borderPen, borderRect) End Using End Sub
如果需要给多个动态生成的Label加自定义边框,只需要在创建每个Label时都绑定Label_CustomPaint事件即可,不需要遍历窗体控件。
内容的提问来源于stack exchange,提问作者kylegreene123
相关产品推荐
相关产品推荐

