Reputation: 272
So, I have some code like this:
Dim box As PictureBox = New PictureBox
Dim Y As Integer
Dim X As Integer
Dim RandomClass As New Random()
Private Sub enspawn_Tick(sender As Object, e As EventArgs) Handles enspawn.Tick
For pos = 30 To 100
Y = RandomClass.Next(530)
X = RandomClass.Next(980)
box.Location = New Point(X, Y)
Next pos
box.Size = New Size(60, 60)
box.Image = VB.NET_Game___1st.My.Resources.Resources.bittenfleax
Controls.Add(box)
End Sub
So basically this will generate random picture boxes around the screen. However, how would I go about making it so when it is clicked (Mouse_Down) it does something.
I do not really have a clue how to approach this. Would it be something along the lines of:
If box_MouseDown Then
MsgBox("Mouse has been pressed on the image box")
End If
I am really unsure. Thanks in advance.
Edit
If it was what I thought it was, would I create a new Private Sub to put it in? Or would it be in Form_Load?
Upvotes: 0
Views: 316
Reputation: 9024
For dynamic controls for need an AddHandler statement to point it's events to a Sub. None of those variables need to be class level. Saves you from holding memory when you don't need to.
Private Sub enspawn_Tick(sender As Object, e As EventArgs) Handles enspawn.Tick
Static RandomClass As New Random
Dim box As New PictureBox
box.Location = New Point(RandomClass.Next(980),RandomClass.Next(530))
box.Size = New Size(60, 60)
box.Image = VB.NET_Game___1st.My.Resources.Resources.bittenfleax
AddHandler box.MouseDown, AddressOf box_MouseDown
Controls.Add(box)
End Sub
Private Sub box_MouseDown(sender As Object, e As MouseEventArgs)
' sender is the PictureBox object
Dim pb As PictureBox = DirectCast(sender, PictureBox)
End Sub
Upvotes: 1