Clip the cursor movement

This code allows you to restrict the cursor movement to a certain area. (Note that this cannot be used as a security measure, as the restriction is cancelled once your application has lost the focus, ie by Alt+Tabbing.)

To use this code, add two command buttons named cmdClip (Caption=Clip to Form) and cmdRestore (Caption=Restore), and then add the code below to the General Declarations section of the form.

Sub cmdClip_Click()
    ' Clip to form's window
    ClipCursorToWindow hWnd
    ' display coordinates
    Call ShowCurrentRect
End Sub
Sub cmdRestore_Click()
    ' restore clip to whole screen
    Call ClipCursorToScreen
    ' display
    Call ShowCurrentRect
End Sub
Sub Form_Load()
    ' display these
    Call ShowCurrentRect
End Sub
Sub ShowCurrentRect()
Dim r As RECT
    'get current clipping region
    Call GetClipCursor(r)
    lblMsg.Caption = "Clipped To: Left=" & Str$(r.left) & "; Right=" & Str$(r.right) & "; Top=" & Str$(r.top) & "; Bottom=" & Str$(r.bottom)
End Sub
Private Sub Form_Unload(Cancel As Integer)
    ' restore clip to what it was at start up
    Call ClipCursorToScreen
    ' exit
    Unload Me
End Sub

Next, add the following code to a module

Type RECT
    left As Long
    top As Long
    right As Long
    bottom As Long
End Type

'// Windows API calls
Declare Sub ClipCursor Lib "User32" (lpRect As RECT)
Declare Sub GetClipCursor Lib "User32" (lprc As RECT)
Declare Sub GetWindowRect Lib "User32" (ByVal hWnd As Long, lpRect As RECT)
Declare Function GetDesktopWindow Lib "User32" () As Long

'// Restore cursor clipping to whole screen
Sub ClipCursorToScreen()
Dim rectScreen As RECT
    '// Get unclipped whole screen for later.
    Call GetWindowRect(GetDesktopWindow(), rectScreen)
    '// Set clipping to rectangle
    Call ClipCursor(rectScreen)
End Sub
'// Clip cursor to window of handle parameter
Sub ClipCursorToWindow(ByVal hWnd As Long)
Dim r As RECT
    '// get window rectangle
    Call GetWindowRect(hWnd, r)
    '// clip to rectangle
    Call ClipCursor(r)
End Sub

You might also like...

Comments

James Crowley James first started this website when learning Visual Basic back in 1999 whilst studying his GCSEs. The site grew steadily over the years while being run as a hobby - to a regular monthly audience ...

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“The generation of random numbers is too important to be left to chance.” - Robert R. Coveyou