有用。例如在一個射擊游戲中,需要限制鼠標在射擊區內移動。
操作步驟
1、建立一個新工程項目,缺省建立窗體FORM1
2、添加一個新模體
3、粘貼下面代碼到新模體
Option ExplicitDeclare Function ClipCursor Lib "user32" (lpRect As Any) As Long
Declare Function ClipCursorClear Lib "user32" Alias "ClipCursor" (ByVal lpRect As Long) As Long
Declare Function ClientToScreen Lib "user32" (ByVal hwnd As Long, lpPoint As POINTAPI) As Long
Type RECT
Left As Long
Top As Long
Right As Long
Bottom As Long
End Type
Type POINTAPI
X As Long
Y As Long
End Type
Public RetValue As Long
Public ClipMode As Boolean
Public Sub SetCursor(ClipObject As Object, Setting As Boolean)
used to clip the cursor into the viewport and
turn off the defa windows cursor
Dim CurrentPoint As POINTAPI
Dim ClipRect As RECT
If Setting = False Then
set clip state back to normal
RetValue = ClipCursorClear(0)
Exit Sub
End If
set current position
With CurrentPoint
.X = 0
.Y = 0
End With
find position on the screen (not the window)
RetValue = ClientToScreen(ClipObject.hwnd, CurrentPoint)
designate clip area
With ClipRect
.Top = CurrentPoint.Y
.Left = CurrentPoint.X
.Right = .Left + ClipObject.ScaleWidth
.Bottom = .Top + ClipObject.ScaleHeight
End With clip it
RetValue = ClipCursor(ClipRect)
End Sub
4、添加一個圖片框控件(PICTURE1)到窗體(FORM1)
5、設置PICTURE1的尺寸和FORM1的一樣大
6、在PICTURE1的CLICK事件中添加以下代碼:
Private Sub Picture1_Click()
ClipMode = Not ClipMode
SetCursor Picture1, ClipMode
End Sub
7、保存工程項目
8、運行程序。在圖片框單擊鼠標,鼠標將被包含在圖片框控件的區域內。要釋放限制狀態只需再次單擊鼠標。
注意:如果釋放限制狀態失敗,鼠標將被永久限制,只能用重新啟動機器來解決。
另一個限制鼠標活動范圍的方法是關閉鼠標,用其他圖象代替光標,例如手槍。