Limit Cursor Movement To Form Boundaries

'Add a module to your project (In the menu choose Project -> Add Module, Then click Open)
'Add 2 Command Buttons to your form.
'Insert this code to the module :

Public Type RECT
left As Integer
top As Integer
right As Integer
bottom As Integer
End Type

Public Type POINT
x As Long
y As Long
End Type

Declare Sub ClipCursor Lib "user32" (lpRect As Any)
Declare Sub GetClientRect Lib "user32" (ByVal hWnd As Long, lpRect As RECT)
Declare Sub ClientToScreen Lib "user32" (ByVal hWnd As Long, lpPoint As POINT)
Declare Sub OffsetRect Lib "user32" (lpRect As RECT, ByVal x As Long, ByVal y As Long)

'Insert this code to your form:

Private Sub Form_Load()
Command1.Caption = "Limit Cursor Movement"
Command2.Caption = "Release Limit"
End Sub

Private Sub Command1_Click()
Dim client As RECT
Dim upperleft As POINT

GetClientRect Me.hWnd, client
upperleft.x = client.left
upperleft.y =
ClientToScreen Me.hWnd, upperleft
OffsetRect client, upperleft.x, upperleft.y
ClipCursor client
End Sub

Private Sub Command2_Click()
ClipCursor ByVal 0&
End Sub

Private Sub Form_Unload(Cancel As Integer)
'If you won't put the code line below in the form's unload event, the cursor will
'be still limited to the last coordinates after the program unloaded.

ClipCursor ByVal 0&
End Sub

Go Back