我想知道是否可以选择控制任何动态创建的对象,例如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
我真的很困惑,我不知道如何让它发挥作用。
答案 0 :(得分:2)
您可以使用许多选项。例如,您可以单击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