vb.net更改动态创建对象的位置



我想知道有没有一个选项可以控制任何动态创建的对象,比如PictureBox?我试图实现的是更改一个或多个PictureBox的位置。这是我正在使用的代码:

Public Class Form1
    Dim MyPictureBox() As PictureBox
    Dim i As Integer
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        ReDim MyPictureBox(5)
        i = i + 1
        Try
            MyPictureBox(i) = New PictureBox()
            With MyPictureBox(i)
                .Name = "PictureBox_" + i.ToString
                .Visible = True
                .Image = My.Resources.test
                .Location = New Point(50 * i, 100)
                .SizeMode = PictureBoxSizeMode.AutoSize
                AddHandler .Click, AddressOf SelectPicture
            End With
            Controls.Add(MyPictureBox(i))
        Catch ex As Exception
            MsgBox("You cannot create any more pictures")
        End Try
    End Sub
    Private Sub SelectPicture(sender As Object, e As EventArgs)
        Dim PictureBoxName As String = sender.name
        If PictureBoxName.Contains("PictureBox_") Then
            Label1.Text = PictureBoxName.ToString
        End If
    End Sub
    Private Sub Form1_MouseClick(sender As Object, e As MouseEventArgs) Handles Me.MouseClick
        If e.Button = MouseButtons.Left Then
            Dim myPictureBox As PictureBox
            Try
                With myPictureBox
                    .Name = Label1.Text.ToString
                    .Location = New Point(PointToClient(MousePosition))
                End With
            Catch ex As Exception
                MsgBox(ex.ToString)
            End Try
        End If
    End Sub
End Class

我真的陷入了困境,我不知道如何让它发挥作用。

您可以使用许多选项。例如,您可以单击PictureBox并将其存储在表单的成员字段中

Private SelectedPictureBox As PictureBox
Private Sub SelectPicture(sender As Object, e As EventArgs)
    SelectedPictureBox = DirectCast(sender, PictureBox)
    Label1.Text = SelectedPictureBox.Name
End Sub

如果你想移动它:

Private Sub Form1_MouseClick(sender As Object, e As MouseEventArgs) Handles Me.MouseClick
    If (Not (SelectedPictureBox Is Nothing)) Then
        SelectedPictureBox.Location = e.Location
    End If
End Sub

此外,您还可以使用Me.Controls.Find:按名称查找控件

Dim c As Control = Me.Controls.Find("YourControlName", True)
'Then you can cast the control to the type that you know 

最新更新