It is possible to do this by creating a Timer
in his Form
, as shown in the figure below:
Then just adjust the properties Interval
and Enabled
of Timer
created, to be able to create a repetitive event (where you will make your PictureBox
move), as in this code:
Option Explicit
Private Indo As Boolean
Private Sub Form_Load()
'Inicialmente, desliga o timer, e configura seu intervalo
'(quanto menor, mais rápido)
Timer1.Enabled = False
Timer1.Interval = 10
End Sub
Private Sub Command1_Click()
If Timer1.Enabled = True Then
Timer1.Enabled = False
Else
Timer1.Enabled = True
End If
End Sub
Private Sub Timer1_Timer()
'10 é um valor arbitrário (quanto maior, mais vai se mover)
If Indo = True Then
Picture1.Left = Picture1.Left + 10
'Se bateu no lado direito, volta
If Picture1.Left >= ScaleWidth - Picture1.Width Then
Indo = False
Picture1.Left = ScaleWidth - Picture1.Width
End If
Else
Picture1.Left = Picture1.Left - 10
'Se bateu no lado esquero, vai de novo
If Picture1.Left <= 0 Then
Indo = True
Picture1.Left = 0
End If
End If
End Sub
Unused Timer
, as requested (not best practice):
Private Sub Command1_Click()
Do While True
If Indo = True Then
Picture1.Left = Picture1.Left + 10
'Se bateu no lado direito, volta
If Picture1.Left >= ScaleWidth - Picture1.Width Then
Indo = False
Picture1.Left = ScaleWidth - Picture1.Width
Exit Do
End If
Else
Picture1.Left = Picture1.Left - 10
'Se bateu no lado esquero, vai de novo
If Picture1.Left <= 0 Then
Indo = True
Picture1.Left = 0
Exit Do
End If
End If
DoEvents
Loop
End Sub
With 4 buttons, one for each direction as requested:
Option Explicit
Private dir As Long
Private Sub cmdUp_Click()
dir = 0
Timer1.Enabled = True
End Sub
Private Sub cmdLeft_Click()
dir = 1
Timer1.Enabled = True
End Sub
Private Sub cmdDown_Click()
dir = 2
Timer1.Enabled = True
End Sub
Private Sub cmdRight_Click()
dir = 3
Timer1.Enabled = True
End Sub
Private Sub Timer1_Timer()
Select Case dir
Case 0
Picture1.Top = Picture1.Top - 10
Case 1
Picture1.Left = Picture1.Left - 10
Case 2
Picture1.Top = Picture1.Top + 10
Case 3
Picture1.Left = Picture1.Left + 10
End Select
End Sub
Instead of deleting your questions, improve them by following the tips given in the comments. After the person updates and improves the post, we can reverse the negative vote that was given.
– brasofilo