Private rect As New Rectangle(0, 0, 25, 25)
Private xIncrement As Integer = 1
Private yIncrement As Integer = 0
Private Sub Form1_Load(ByVal sender As Object, _
ByVal e As EventArgs) Handles MyBase.Load
Me.Timer1.Start()
End Sub
Private Sub Timer1_Tick(ByVal sender As Object, _
ByVal e As EventArgs) Handles Timer1.Tick
'Mark the old rectangle to be erased.
Me.Invalidate(Rectangle.Inflate(Me.rect, 1, 1))
'Shift the rectangle.
Me.rect.Offset(Me.xIncrement, Me.yIncrement)
'Mark the new rectangle to be drawn.
Me.Invalidate(Rectangle.Inflate(Me.rect, 1, 1))
'Do the drawing.
Me.Update()
'Change the direction of movement if a boundary has been reached.
If Me.xIncrement = 1 AndAlso Me.rect.Right >= Me.ClientSize.Width - 1 Then
Me.xIncrement = 0
Me.yIncrement = 1
ElseIf Me.yIncrement = 1 AndAlso Me.rect.Bottom >= Me.ClientSize.Height - 1 Then
Me.xIncrement = -1
Me.yIncrement = 0
ElseIf Me.xIncrement = -1 AndAlso Me.rect.Left <= 0 Then
Me.xIncrement = 0
Me.yIncrement = -1
ElseIf Me.yIncrement = -1 AndAlso Me.rect.Top <= 0 Then
Me.xIncrement = 1
Me.yIncrement = 0
End If
End Sub
Private Sub Form1_Paint(ByVal sender As Object, _
ByVal e As PaintEventArgs) Handles Me.Paint
'Draw the rectangle.
e.Graphics.DrawRectangle(Pens.Black, Me.rect)
End Sub