AllAPI Network - The KPD-Team

Allapi Network

 API List

API Resources
 Tips & Tricks
 VB Tutorials
 Error Lookup
Misc Stuff
 VB examples
 VB Tools
 VB Links
 Top Downloads
This Site
 Search Engine
 Contact Form

Donate to

How can I limit cursor movement inside a form ?

You might want to limit the cursor movement area if you have drag-and-drop
functionality within a form and you only want the user to drag an item
inside a form.

The ClipCursor function confines the cursor to a rectangular area on the
screen. If a subsequent cursor position (set by the SetCursorPos function
or the mouse) lies outside the rectangle, Windows automatically adjusts the
position to keep the cursor inside the rectangular area.

The form borders serve as the rectangular area for the ClipCursor function.
To get the size of the form, use the GetClientRect function. This function
retrieves the coordinates of a window's client area. The coordinates are
relative to the upper-left corner of a window's client area; the
coordinates of the upper-left corner are (0,0). This means you will have to
convert the client coordinates to screen coordinates.

The ClientToScreen function converts the client coordinates of a specified
point to screen coordinates. The last function used is the OffsetRect
function. The OffsetRect function moves the specified rectangle by the
specified offsets.

NOTE: If you unload the form after executing the ClipCursor function, the
cursor will still be limited to the last coordinates of the now-unloaded
form. To prevent this behavior, calling the ClipCursor function with a null
argument in the Form_Unload event is recommended.

Private Type RECT
left As Integer
top As Integer
right As Integer
bottom As Integer
End Type
Private Type POINT
x As Long
y As Long
End Type
Private Declare Sub ClipCursor Lib "user32" (lpRect As Any)
Private Declare Sub GetClientRect Lib "user32" (ByVal hWnd As Long, lpRect As RECT)
Private Declare Sub ClientToScreen Lib "user32" (ByVal hWnd As Long, lpPoint As POINT)
Private Declare Sub OffsetRect Lib "user32" (lpRect As RECT, ByVal x As Long, ByVal y As Long)
Private Sub Form_Load()
Command1.Caption = "Limit Cursor Movement"
Command2.Caption = "Release Limit"
End Sub
Private Sub Command1_Click()
'Limits the Cursor movement to within the form.
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()
'Releases the cursor limits
ClipCursor ByVal 0&
End Sub
Private Sub Form_Unload(Cancel As Integer)
'Releases the cursor limits
ClipCursor ByVal 0&
End Sub



Copyright © 1998-2007, The Team - Privacy statement
Did you find a bug on this page? Tell us!
This site is located at