Members

Technology Zones

IBM Learning Center

Articles

Hosted By

MaximumASP

Info

Rated
Read 16,727 times

Related Categories

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

James first started writing tutorials on Visual Basic in 1999 whilst starting this website (then known as VB Web). Since then, the site has grown rapidly, and James has written numerous tutorials, articles and reviews on VB, PHP, ASP and C#. In October 2003, James formed the company Developer Fusion Ltd, which owns this website, and also offers various development services. In his spare time, he's a 3rd year undergraduate studying Computer Science in the UK. He's also a Visual Basic MVP.

Comments

  • Re: [223] Clip the cursor movement

    Posted by jayasenthur on 29 Sep 2006

    Hi ,


    I tried converting  this code into VB .NET. But I faced  the following error


     "A call to PInvoke function 'limitcursor!limitcursor.Form1::GetClipCursor' has unba...