首页 > 解决方案 > 如何更改在运行时创建的标签边框的颜色?

问题描述

下面的代码用于动态创建一个名为 的标签Title,它将属性设置为与标签相关的字体、前景色等Text

 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.Fixed3D
    Me.Size = New System.Drawing.Size(900, 700)
End Sub

这部分应该为标签的边框着色,但它没有这样做。

Private Sub Title_paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Me.Paint
    Dim g As Graphics = e.Graphics
    Dim pen As New Pen(Color.Red, 4.0)
    For Each ctr As Control In Me.Controls
        If TypeOf ctr Is Label Then
            g.DrawRectangle(pen, New  _
                            Rectangle(ctr.Location, ctr.Size))
        End If
    Next
    pen.Dispose()
End Sub

标签: vb.netwinforms

解决方案


您应该订阅Paint您的标签事件(或标签,如果您添加多个;对所有事件使用相同的事件处理程序)。

当引发 Paint 事件时,sender对象是引发事件的控件,因此您可以强制sender转换为ControlLabel(我们只需要ClientRectangle属于Control该类的属性值,因此您可以对其他控件使用相同的事件处理程序不是Label;例如,面板)。

现在,如果您希望您的标签自动调整其文本内容的大小,您需要设置AutoSize = True:标签将在执行其布局时自动调整大小(在您将其添加到容器之后 - 此处的表单)。
因此,要将其显示在表单的中间,请在将其添加到集合并更改表单大小Location后设置其属性。Controls

如果您想设置一个特定的Size,请不要设置AutoSize = FalseSize明确设置属性和Location更改表单大小后的属性(看起来您想在运行时调整表单大小)。

Public Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    MyBase.OnLoad(e)
    Dim lblTitle As New Label() With {
        .AutoSize = True,
        .BackColor = Color.Black,
        .BorderStyle = BorderStyle.None,
        .Font = New Font("Times New Roman", 30, FontStyle.Bold),
        .ForeColor = Color.Red,
        .Text = "BROKERS"
    }

    AddHandler lblTitle.Paint, AddressOf TitleLabel_Paint

    ClientSize = New Size(900, 700)
    Controls.Add(lblTitle)
    lblTitle.Location = New Point(ClientSize.Width - lblTitle.Width) \ 2, 
                                 (ClientSize.Height - lblTitle.Height) \ 2)
End Sub

Private Sub TitleLabel_Paint(sender As Object, e As PaintEventArgs)
    If sender Is Nothing Then Return
    Dim ctrl = DirectCast(sender, Control)
    Using pen As New Pen(Color.Red, 4)
        e.Graphics.DrawRectangle(pen, ctrl.ClientRectangle)
    End Using
End Sub

推荐阅读