Stop The Cursor From Moving Off Your Form

The ClipCursor API call lets you define a region of the screen and restrict the cursor to within that region. This lets you prevent the user from clicking outside of your application's form.

A few words of caution, this doesn't work when running multiple monitiors. Also, you may experience problems when switching tasks and coming back to the program and the clipped area may prevent you from reaching certain areas of another program. Typically, pressing the Windows-Key to display the Start menu should clear the clip area.

You can solve these problems by subclassing the form (see my subclassing page) and processing WM_ACTIVATE to clear and reassign the clip area.

Download Source Code

Form Code

Add this code to the Declarations Section:

Dim lTwipsX As Long
    Dim lTwipsY As Long
       
    Private Type RECT
      Left As Long
      Top As Long
      Right As Long
      Bottom As Long
    End Type
    
    Dim RectArea As RECT
    '
    ' The ClipCursor function confines the cursor to
    ' a rectangular area on the screen.
    '
    Private Declare Function ClipCursor Lib "user32" (lpRect As Any) As Long

Add this to the form_Load event:

    Private Sub Form_Load()
        lTwipsX = Screen.TwipsPerPixelX
        lTwipsY = Screen.TwipsPerPixelY
        End Sub

Add a button named cmdTrap with this code:

Private Sub cmdTrap_Click()
   Form1.Caption = "Cursor Clipped to the Form"
    
   With RectArea
     .Left = Form1.Left / lTwipsX
     .Top = Form1.Top / lTwipsY
     .Right = .Left + Form1.Width / lTwipsX
     .Bottom = .Top + Form1.Height / lTwipsY
  End With

  Call ClipCursor(RectArea)
End Sub
    

Add a button named cmdRelease with this code:

Private Sub cmdRelease_Click()
    Form1.Caption = "Cursor Released"
    
    With RectArea
        .Left = 0
        .Top = 0
        .Right = Screen.Width / lTwipsX
        .Bottom = Screen.Height / lTwipsY
    End With
    Call ClipCursor(RectArea)
End Sub
    
Instructions

Download the source code. Press F5 to run the program. Move the cursor anywhere on the screen. Click the Trap button and notice that you cannot move the cursor outside of the form. Click the Release button to restore normal cursor movement.




About TheScarms
About TheScarms


Sample code
version info

If you use this code, please mention "www.TheScarms.com"

Email this page


© Copyright 2024 TheScarms
Goto top of page