这个技巧将向您展示如何使用捕捉光标的API函数阻止鼠标指针移出窗体。
注意!:如果窗体的BorderStyle属性被设为sizeable(2或5),则当你改变窗体的大小时鼠标就会“逃脱”程序的监控!因此你最好把BorderStyle设为0、1、3或4。
步骤:
把以下代码添加如模块:
Option Explicit
Type RECT
Left As Long
Top As Long
Right As Long
Bottom As Long
End Type
Declare Function ClipCursor Lib "user32" _
(lpRect As Any) As Long
Public Sub DisableTrap(CurForm As Form)
Dim erg As Long
'声明过程变量
'设置新坐标
Dim NewRect As RECT
CurForm.Caption = "释放鼠标"
With NewRect
.Left = 0&
.Top = 0&
.Right = Screen.Width / Screen.TwipsPerPixelX
.Bottom = Screen.Height / Screen.TwipsPerPixelY
End With
erg& = ClipCursor(NewRect)
End Sub
Public Sub EnableTrap(CurForm As Form)
Dim x As Long, y As Long, erg As Long
'声明过程变量
'设置新坐标
Dim NewRect As RECT
'得到TwipsperPixel
'窗体的ScaleMode必须设为Twips!!!
x& = Screen.TwipsPerPixelX
y& = Screen.TwipsPerPixelY
CurForm.Caption = "捕捉鼠标"
'设置光标的范围
With NewRect
.Left = CurForm.Left / x&
.Top = CurForm.Top / y&
.Right = .Left + CurForm.Width / x&
.Bottom = .Top + CurForm.Height / y&
End With
erg& = ClipCursor(NewRect)
End Sub
2、在窗体上添加两个命令按钮(Command Button)。
3、把以下代码添加如Form1。
Private Sub Command1_Click()
EnableTrap Form1
End Sub
Private Sub Command2_Click()
DisableTrap Form1
End Sub
Private Sub Form_Unload(Cancel As Integer)
'程序结束时释放鼠标。
DisableTrap Form1
End Sub
文章来源于领测软件测试网 https://www.ltesting.net/
版权所有(C) 2003-2010 TestAge(领测软件测试网)|领测国际科技(北京)有限公司|软件测试工程师培训网 All Rights Reserved
北京市海淀区中关村南大街9号北京理工科技大厦1402室 京ICP备10010545号-5
技术支持和业务联系:info@testage.com.cn 电话:010-51297073