窗体上放一个Timer控件,再放一个PictureBox,然后粘贴如下代码:
Private Declare Function GetAsyncKeyState Lib "user32" (ByVal vKey As Long) As Integer '检测键盘按键状态的API
Private Sub Form_Load()
Timer1.Enabled = True
Timer1.Interval = 1
End Sub
Private Sub Timer1_Timer()
If GetAsyncKeyState(vbKeyLeft) Or GetAsyncKeyState(vbKeyA) Then
If Picture1.Left > 0 - Picture1.Width Then Picture1.Left = Picture1.Left - 15 Else Picture1.Left = Me.Width
End If
If GetAsyncKeyState(vbKeyRight) Or GetAsyncKeyState(vbKeyD) Then
If Picture1.Left < Me.Width Then Picture1.Left = Picture1.Left + 15 Else Picture1.Left = 0 - Picture1.Width
End If
If GetAsyncKeyState(vbKeyUp) Or GetAsyncKeyState(vbKeyW) Then
If Picture1.Top > 0 - Picture1.Height Then Picture1.Top = Picture1.Top - 15 Else Picture1.Top = Me.Height
End If
If GetAsyncKeyState(vbKeyDown) Or GetAsyncKeyState(vbKeyS) Then
If Picture1.Top < Me.Height Then Picture1.Top = Picture1.Top + 15 Else Picture1.Top = 0 - Picture1.Height
End If
End Sub
运行即可,使用方向键或WASD键,图片会移动。