程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> Visual Basic語言 >> VB綜合教程 >> vb怎樣限制鼠標移動

vb怎樣限制鼠標移動

編輯:VB綜合教程

  本文介紹如何限制鼠標在窗口的指定范圍內移動。這個技術在需要防止用戶鼠標在指定區域內活動時非常

  有用。例如在一個射擊游戲中,需要限制鼠標在射擊區內移動。

  操作步驟

  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、運行程序。在圖片框單擊鼠標,鼠標將被包含在圖片框控件的區域內。要釋放限制狀態只需再次單擊鼠標。

  注意:如果釋放限制狀態失敗,鼠標將被永久限制,只能用重新啟動機器來解決。

  另一個限制鼠標活動范圍的方法是關閉鼠標,用其他圖象代替光標,例如手槍。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved