设定Mouse 在某个固定范围

原始来源:  cww

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
Declare Function ShowCursor Lib "user32" (ByVal bShow As Long) As Long
Declare Function SetCursorPos Lib "user32" (ByVal x As Long, _
        ByVal y As Long) As Long
Declare Function GetWindowRect Lib "user32" Alias "GetWindowRect" _
        (ByVal hwnd As Long, lpRect As RECT) As Long

'设定Mouse可移动的围是在某个control项之内
Public Function toLockCursor(ByVal ctlHwnd As Long) As Boolean
Dim rect5 As RECT
Dim res As Long
GetWindowRect ctlHwnd, rect5 '取得window的四个角
rect5.Top = rect5.Top
rect5.Left = rect5.Left
rect5.Bottom = rect5.Bottom
rect5.Right = rect5.Right
SetCursorPos (rect5.Top + rect5.Bottom) \ 2, (rect5.Left + rect5.Right) \ 2

res = ClipCursor(rect5)
If res = 1 Then
   toLockCursor = True
Else
   toLockCursor = False
End If
End Function

'设定Mouse移动的围为个萤幕
Public Sub toUnLockCursor()
Dim rscreen As RECT
rscreen.Top = 0
rscreen.Left = 0
rscreen.Right = Screen.Width \ Screen.TwipsPerPixelX
rscreen.Bottom = Screen.Height \ Screen.TwipsPerPixelY
ClipCursor rscreen
End Sub

例如:设定Mouse只能在Form的范围
Private Sub Command1.Click()
 Call toLockCursor(Me.hWnd)
End Sub
Private Sub Command2.Click()
 Call toUnLockCursor()
End Sub