Restrict Mouse Movement to an Area of the Desktop

This tip shows you how to ensure a cursor remains within a certain rectangle on the screen. Note that if the user uses Alt-Tab to switch to another application, the clipping cursor is cleared.

Start a new project in VB. Add a new module, and add the following code:

' API Declarations: 
Private Type POINTAPI 
    X As Long 
    Y As Long 
End Type 
Private Type RECT 
    eft As Long 
    op As Long 
    ight As Long 
    ottom As Long 
End Type 
Private Declare Sub ClipCursorRect Lib "user32" _
    Alias "ClipCursor" _
    (lpRect As RECT) 
Private Declare Sub ClipCursorClear Lib "user32" _
    Alias "ClipCursor" _
    (ByVal lpRect As Long) 
Private Declare Function ClientToScreen Lib "user32" _
    (ByVal hWnd As Long, lpPoint As POINTAPI) As Long 

Public Sub RestrictCursor( _ 
        ByVal lLeft As Long, _ 
        ByVal lTop As Long, _ 
        ByVal lWidth As Long, _ 
        ByVal lHeight As Long, _ 
        Optional ByRef oPositionTo As Object = Nothing _ 
Dim tR As RECT 
    ' Convert positions into a rectangle in pixels: 
    tR.Left = lLeft \ Screen.TwipsPerPixelX 
    tR.Top = lTop \ Screen.TwipsPerPixelY 
    tR.Right = (lLeft + lWidth) \ Screen.TwipsPerPixelX 
    tR.Bottom = (lLeft + lHeight) \ Screen.TwipsPerPixelY 
    ' Validate optional parameter: 
    If oPositionTo Is Nothing Then Set oPositionTo = Screen 
    ' If positions refer to an form or control, then 
    ' convert the coordinates to the screen position: 
    If Not oPositionTo Is Screen Then 
        tP.X = tR.Left 
        tP.Y = tR.Top 
        ClientToScreen oPositionTo.hWnd, tP 
        tR.Left = tP.X 
        tR.Top = tP.Y 
        tP.X = tR.Right 
        tP.Y = tR.Bottom 
        ClientToScreen oPositionTo.hWnd, tP 
        tR.Right = tP.X 
        tR.Bottom = tP.Y 
    End If 
    ' Set the cursor clipping rectangle: 
    ClipCursorRect tR 
End Sub 
Public Sub ClearRestrictCursor() 
    ClipCursorClear 0
End Sub 

Now you can create a test project. Add a Picture Box to the form in your project, and draw a Check Box inside the Picture Box (note: put the check box inside the picture otherwise you won't be able to get at it whilst the cursor is being restricted!).

Add the following code to the Check box click event:

Private Sub Check1_Click() 
    If (Check1.Value = Checked) Then 
        ' Restrict the cursor so it can't move 
        ' out of the picture: 
        RestrictCursor 0, 0, Picture1.Width, Picture1.Height, Picture1 
        ' Stop restricting the cursor: 
    End If
End Sub

Run the project. You will find that when you click the Check Box you can't move the mouse pointer outside the Picture Box.