From the requirement given in the question it appears that a
single square
has to move in the
Tick
event of the timer. But as seen from the code given in the question, a new
TheSquare
PictureBox
is instantiated each time the
Tick
event fires and this new
PictureBox
is being added to the
Panel1
, which makes the
Panel1
to be cluttered with so many picture boxes. Further, from the code
TheSquare.Location = New Point(Unitmaker.Location.X, Unitmaker.Location.Y - 10)
TheSquare.Location = New Point(TheSquare.Location.X, TheSquare.Location.Y - 10)
the second line is redundant, as the Location of
TheSquare
is reassigned by only decrementing the Y value, which could be achieved in the first statement itself by giving
Y - 20
.
So, I think a
PictureBox
can be created at
Class
level and it may be moved by assigning new location in the
Tick
event.
The following sample code may be helpful
Public Class Form1
Dim TheSquare As New PictureBox()
Dim WithEvents UnitSender As New Timer()
Dim Panel1 As New Panel
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
TheSquare.Size = New Size(15, 15)
Panel1.Dock = DockStyle.Fill
TheSquare.BackColor = Color.Red
Panel1.Controls.Add(TheSquare)
Controls.Add(Panel1)
UnitSender.Enabled = True
Me.Size = New Size(100, 125)
End Sub
Private Sub UnitSender_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles UnitSender.Tick
Dim newX As Integer = TheSquare.Location.X
Dim newY As Integer = TheSquare.Location.Y + 10
If newY > (Panel1.Height - TheSquare.Height) Then
newY = 0
newX += 10
If newX > (Panel1.Width - TheSquare.Width) Then
newX = 0
End If
End If
TheSquare.Location = New Point(newX, newY)
End Sub
End Class
To run the sample, create a
Windows Forms application
, replace the contents of the
Form1.vb
file with the above code and run the application.