新建一工程,放一个按钮command1,放一个时钟timer1,拷贝下列代码运行,按按钮一下会发现鼠标随机移动,碰到边界会反弹,再按按钮一下(或回车键)会停止。
‘*****************************拷贝下列代码*****************************************
Private Type POINTAPI x As Long y As Long End Type Private Declare Function GetCursorPos Lib "user32" (lpPoint As POINTAPI) As Long Private Declare Function SetCursorPos Lib "user32" (ByVal x As Long, ByVal y As Long) As Long Dim rndX As Integer, rndY As Integer ‘定义随机移动方向和速率 Private Sub Command1_Click() If rndX <> 0 And rndY <> 0 Then rndX = 0 rndY = 0 Exit Sub End If While rndX = 0 rndX = Rnd * 20 - 10 Wend While rndY = 0 rndY = Rnd * 20 - 10 Wend End Sub Private Sub Form_Load() Timer1.Interval = 10 End Sub Private Sub Timer1_Timer() Dim pos As POINTAPI, x As Long, y As Long If rndX = 0 And rndY = 0 Then Rnd Exit Sub End If GetCursorPos pos x = pos.x + rndX y = pos.y + rndY If x < 20 Then x = 20 rndX = rndX * (-1) End If If x >= Screen.Width / 15 - 60 Then x = Screen.Width / 15 - 60 rndX = rndX * (-1) End If If y < 20 Then y = 20 rndY = rndY * (-1) End If If y >= Screen.Height / 15 - 100 Then y = Screen.Height / 15 - 100 rndY = rndY * (-1) End If SetCursorPos x, y End Sub
转自:http://bbs.bccn.net/thread-407793-1-1.html
时间: 2024-10-22 16:10:07