用图像

时间:2016-03-12 17:07:52

标签: vb.net button

我有很大的问题。 我有122个按钮,他们必须有我们的图像,手动它将需要一年"年" 。我想自动执行此操作,示例Button1命名为1,我在资源中将照片命名为1.png,button2命名为2,资源为2.png。如何自动填写所有这些按钮? 感谢您的帮助:)

1 个答案:

答案 0 :(得分:0)

在循环中创建按钮很简单,但为每个按钮添加唯一的处理程序是一件痛苦的事。你最好创建一个按钮,复制它并将其粘贴121次。然后,在您的程序中创建一个类似下面的子项,将背景图像添加到每个按钮。

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    AddBackgroundToButtons
End Sub

Private Sub AddBackgroundToButtons()
    For Each control As Object In Me.Controls
        Dim btn As Button
        If TypeOf control Is Button Then
            btn = CType(control, Button)
        Else
            Continue For
        End If
        Dim btnNum As Integer
        If Integer.TryParse(btn.Name.Substring(6), btnNum) Then
            If btnNum >= 1 AndAlso btnNum <= 122 Then
                Dim img As Image = New Bitmap("K:\png\" & btnNum.ToString & ".png")
                btn.BackgroundImageLayout = ImageLayout.Center
                btn.BackgroundImage = img
            End If
        End If
    Next
End Sub

如果按钮位于Groupbox或其他容器内,则可能需要将Me.Controls更改为Me.GroupBox1.Controls