×

捕捉窗体的鼠标

Kalet Kalet 发表于2009-03-20 12:00:14 浏览279 评论0

抢沙发发表评论

这个技巧将向您展示如何使用捕捉光标的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


群贤毕至

访客