本实例演示利用 API 函数ClipCursor来把鼠标锁定到指定的窗口中。
实例代码如下:
'用户昵称: 留下些什么
'个人简介: 一个会做软件的货代
'CSDN网址:https://blog.csdn.net/zezese
Option Explicit
Private Declare Function ClientToScreen Lib "user32.dll" (ByVal hWnd As Long, ByRef lpPoint As POINTAPI) As Long
Private Type POINTAPI
x As Long
y As Long
End Type
Private Declare Function GetClientRect Lib "user32.dll" (ByVal hWnd As Long, ByRef lpRect As RECT) As Long
Private Type RECT
Left As Long
Top As Long
Right As Long
Bottom As Long
End Type
Private Declare Function ClipCursor Lib "user32.dll" (ByRef lpRect As Any) As Long
Private Sub cmdLock_Click()
LockCursorInWindow Me.hWnd
End Sub
Private Sub cmdUnlock_Click()
UnLockCursor
End Sub
Public Sub LockCursorInWindow(ByVal hWnd As Long)
Dim CurrentPoint As POINTAPI
'获取窗体顶点在屏幕中的位置
CurrentPoint.x = 0
CurrentPoint.y = 0
Call ClientToScreen(hWnd, CurrentPoint)
'获取窗体区域
Dim rClient As RECT
GetClientRect hWnd, rClient
'转换窗体区域为屏幕区域
Dim ClipRect As RECT
With ClipRect
.Top = CurrentPoint.y
.Left = CurrentPoint.x
.Right = .Left + (rClient.Right - rClient.Left)
.Bottom = .Top + (rClient.Bottom - rClient.Top)
End With ' clip it
'设置鼠标区域
ClipCursor ClipRect
End Sub
Public Sub UnLockCursor()
ClipCursor ByVal 0&
End Sub