簡體   English   中英

如何將事件添加到通過單擊按鈕 VB.NET 動態創建的 PictureBox

[英]How can I add events to a PictureBox dynamically created by clicking button VB.NET

使用文本框添加我動態創建的數字,例如表單中的 5 個圖片框,如下所示:

Sub CreateImages()
    Dim pb As New PictureBox
    Dim i As Integer = TextBoxNumberImages.Text
    Dim Z As Integer = 10

    pb.Top = 50
    pb.Left = 50
    pb.Tag = Color.Black
    pb.BackColor = Color.Red

    For i = 1 To i
        pb = New PictureBox
        pb.Width = 120
        pb.Height = 330
        pb.Left += Z
        pb.Tag = False
        pb.Name = "Image" + Str(i)
        pb.BorderStyle = BorderStyle.FixedSingle

        pb.BackColor = Color.Green
        AddHandler pb.Click, AddressOf _Click

        Me.Controls.Add(pb)
        pb.Refresh()
        Z += 125
    Next
End Sub

然后,在創建圖片框后,單擊每個..使用AddHandler pb.Click, AddressOf _Click我得到焦點和 3 個按鈕來處理當前圖片框(只需增加/減少或剪切成兩部分),使用以下代碼:

Public Sub _Click(ByVal sender As Object, ByVal e As EventArgs)
    Dim pb As PictureBox = DirectCast(sender, PictureBox)
    Dim selected As Boolean = DirectCast(pb.Tag, Boolean)

         
    Dim d As Integer
    For d = 1 To TextBoxNumberImages.Text
        If pb.Name = "Image" + Str(d) Then
            NOMEPIC = pb.Name
            pb.BackColor = Color.Blue
            '   MsgBox(pb.Location.X & "X")
            '   MsgBox(pb.Location.Y & "Y")
            BtnAdd.Top = pb.Location.Y + 330
            BtnAdd.Left = pb.Location.X
            BtnSub.Top = pb.Location.Y + 330
            BtnSub.Left = pb.Location.X + 40
            BtnNew.Top = pb.Location.Y + 330
            BtnNew.Left = pb.Location.X + 80
            Label1.Top = pb.Location.Y + 360
            Label1.Left = pb.Location.X
            Label1.Text = "Art. " & d
            txtArt.Top = pb.Location.Y + 380
            txtArt.Left = pb.Location.X
        End If
    Next
    BtnAdd.Visible = True
    BtnSub.Visible = True
    BtnNew.Visible = True
    Label1.Visible = True
    txtArt.Visible = True
    pb.Refresh()

現在我想通過 3 個按鈕來管理它們(“+”增大尺寸“-”減小尺寸 e cut...)但我不知道如何讓圖片框聚焦(參與)。

只需保留對上次單擊的 PictureBox 的引用,然后在按鈕處理程序中對其進行操作

Private selectedPictureBox As PictureBox

Private Sub _Click(sender As Object, e As EventArgs)
    selectedPictureBox = DirectCast(sender, PictureBox)
    ' ...
End Sub

Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
    If selectedPictureBox Is Nothing Then Exit Sub
    selectedPictureBox.Width += 1
    selectedPictureBox.Height += 1
End Sub

Private Sub btnSub_Click(sender As Object, e As EventArgs) Handles btnSub.Click
    If selectedPictureBox Is Nothing Then Exit Sub
    selectedPictureBox.Width -= 1
    selectedPictureBox.Height -= 1
End Sub

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM