vb.net - 如何更改在运行时创建的标签边框的颜色?
问题描述
下面的代码用于动态创建一个名为 的标签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
解决方案
您应该订阅Paint
您的标签事件(或标签,如果您添加多个;对所有事件使用相同的事件处理程序)。
当引发 Paint 事件时,sender
对象是引发事件的控件,因此您可以强制sender
转换为Control
或Label
(我们只需要ClientRectangle
属于Control
该类的属性值,因此您可以对其他控件使用相同的事件处理程序不是Label
;例如,面板)。
现在,如果您希望您的标签自动调整其文本内容的大小,您需要设置AutoSize = True
:标签将在执行其布局时自动调整大小(在您将其添加到容器之后 - 此处的表单)。
因此,要将其显示在表单的中间,请在将其添加到集合并更改表单大小Location
后设置其属性。Controls
如果您想设置一个特定的Size
,请不要设置AutoSize = False
,Size
明确设置属性和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
推荐阅读
- php - 在 appengine 上使用 php 将大文件下载到云存储
- python - Matplotlib xticklabels 显示年份而不是月份
- c - 错误:非法指令。Mips 交叉编译器
- python - 根据条件比较熊猫数据框行
- neural-network - 如何在 Keras 中为 Sequential 模型实现损失函数(Intersection over Union)?
- php - SQL SELECT 返回数组,但 PHP 认为它为空
- java - Java 正则表达式模式根据分隔符字符串“|-|”拆分字符串
- r - 闪亮的应用程序与服务器断开连接(闪亮的服务器专业版试用版)
- php - laravel 5.6:会话在 Chorme 中不起作用,但在 Firefox 中起作用
- java - JPA:SQL 错误:1062,SQLState:23000 错误:重复条目: