用VB让鼠标指针“舞”起来
软件世界
想让你的鼠标指针在屏幕上疯狂舞蹈吗?是不是觉得很有趣,那就赶快行动吧!
首先,新建一个“标准 EXE”工程,然后添加一个模块Module1。在这里,将用到三个API函数,
分别是:Public Declare Function GetCursorPos Lib "user32" (lpPoint As POINTAPI) As Long
Public Declare Function SetCursorPos Lib "user32" (ByVal x As Long,ByVal y As Long) As Long
Private Declare Function GetKeyState Lib "user32" (ByVal nVirtKey As Long) As Integer,
可以用Microsoft Visual Basic自带的API浏览器找到。在Module1中编写如下程序:
Option Explicit
Private Const VK_ESCAPE = &H1B '设置Esc键的键值
Public go As Boolean '设置标志go
Public Type POINTAPI
x As Long
y As Long
End Type
Public Declare Function GetCursorPos Lib "user32" (lpPoint As POINTAPI) As Long
Public Declare Function SetCursorPos Lib "user32" (ByVal x As Long, ByVal y As Long) As Long
Private Declare Function GetKeyState Lib "user32" (ByVal nVirtKey As Long) As Integer
'按下Esc键,flag的值会改变,以便让指针停止抖动或继续抖动
Public Function flag() As Integer
flag = GetKeyState(VK_ESCAPE)
End Function
在窗体中加入一个Timer控件,把Interval设为30,这是指针的抖动频率。
双击窗体,在弹出的Code中编写如下程序:
Option Explicit
Dim p As POINTAPI
Private Sub Form_Load()
go = True'设标志为:True
Hide '隐藏窗体
End Sub
'让指针随机抖动
Private Sub Timer1_Timer()
If flag = 0 Then '调用函数flag
go = True
Else: go = False
End If
If go = True Then
Dim i, j, k1, k2 As Integer
GetCursorPos p '获得指针坐标
i = Int(12 * Rnd()): j = Int(12 * Rnd( '获得0--11之间的随机整数
k1 = (-1) ^ i * 10: k2 = (-1) ^ j * 10 '这里是关键,用-1的乘方取随机的正负,10为指针的振幅
p.x = p.x + k1: p.y = p.y + k2 '改变指针位置
SetCursorPos p.x, p.y '设置新的指针位置
End If
End Sub
好了,现在按下F5,怎么样,指针开始起舞了吧!按下Esc,恢复正常,再按下Esc,就又会抖动。
注:以上内容在VB6.0,WindowXp环境下运行并通过。