Moving an Object

Enter your search terms Submit search form

 


 

 

This is program that can move an object to the left or right by pressing the left arrow key and the right arrow key on the keyboard  respectively. In order to do this, you can insert a shape into the form, then write the codes under the keyDown Sub procedure. The key code for the right arrow is 39 whereas the key code for the left arrow key is 37.

You can make the object move by using the Left property of the object. Left is the distance between the object and the left most border of the  form. SO the statement Shape1.Left=Shape1.Left+100 will move it further from the left by 100 twips each the user press the right arrow key. When the object move beyond the right border, you bring it back to the left border by reversing the objec using Shape1.Left=-Shape1.Width, making it like appearing from the left border. The rest of the logics follow.

Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)
If KeyCode = 39 Then
Shape1.Left = Shape1.Left + 100
If Shape1.Left > Form1.Width Then
Shape1.Left = -Shape1.Width
End If
End If
If KeyCode = 37 Then
Shape1.Left = Shape1.Left - 100
If Shape1.Left < -Shape1.Width Then
Shape1.Left = Form1.Width
End If
End If
End Sub

 

 

 

 

 

 [Back to VBToday]