我寫了這樣的事情在網頁上拖動的div ...
一般的做法是,以節省鼠標按下座標,獲得座標在mouseup上,並根據差異移動對象的位置。
下面是一些示例代碼:
我做了一個DragInfo
類,保持最初的鼠標COORDS和初始位置。然後我保存這些傢伙中的一個控件的Tag
上鼠標按下事件:
Public Class DragInfo
Public Property InitialMouseCoords As Point
Public Property InitialLocation As Point
Public Sub New(ByVal MouseCoords As Point, ByVal Location As Point)
InitialMouseCoords = MouseCoords
InitialLocation = Location
End Sub
Public Function NewLocation(ByVal MouseCoords As Point) As Point
Dim loc As New Point(InitialLocation.X + (MouseCoords.X - InitialMouseCoords.X), InitialLocation.Y + (MouseCoords.Y - InitialMouseCoords.Y))
Return loc
End Function
End Class
我的測試控制僅僅是我從工具箱中把一個面板。這可能是我猜想的任何事情。這裏是我的鼠標按下,鼠標移動和鼠標鬆開事件的處理程序面板(Panel1
):
Private Sub Panel1_MouseDown(sender As System.Object, e As System.Windows.Forms.MouseEventArgs) Handles Panel1.MouseDown
Panel1.Tag = New DragInfo(Form.MousePosition, Panel1.Location)
End Sub
Private Sub Panel1_MouseMove(sender As System.Object, e As System.Windows.Forms.MouseEventArgs) Handles Panel1.MouseMove
If Panel1.Tag IsNot Nothing Then
Dim info As DragInfo = CType(Panel1.Tag, DragInfo)
Dim newLoc As Point = info.NewLocation(Form.MousePosition)
If Me.ClientRectangle.Contains(New Rectangle(newLoc, Panel1.Size)) Then Panel1.Location = newLoc
End If
End Sub
Private Sub Panel1_MouseUp(sender As System.Object, e As System.Windows.Forms.MouseEventArgs) Handles Panel1.MouseUp
Panel1.Tag = Nothing
End Sub
你去那裏!這樣可行。請注意,mousemove方法檢查控件是否在窗體的clientrectangle內。
或者,更通用的路要走:
Private Sub MakeDraggable(ByVal Control As Control)
AddHandler Control.MouseDown, Sub(sender As Object, e As MouseEventArgs) StartDrag(Control)
AddHandler Control.MouseMove, Sub(sender As Object, e As MouseEventArgs) Drag(Control)
AddHandler Control.MouseUp, Sub(sender As Object, e As MouseEventArgs) StopDrag(Control)
End Sub
Private Sub StartDrag(ByVal Control As Control)
Control.Tag = New DragInfo(Form.MousePosition, Control.Location)
End Sub
Private Sub Drag(ByVal Control As Control)
If Control.Tag IsNot Nothing AndAlso TypeOf Control.Tag Is DragInfo Then
Dim info As DragInfo = CType(Control.Tag, DragInfo)
Dim newLoc As Point = info.NewLocation(Form.MousePosition)
If Me.ClientRectangle.Contains(New Rectangle(newLoc, Control.Size)) Then Control.Location = newLoc
End If
End Sub
Private Sub StopDrag(ByVal Control As Control)
Control.Tag = Nothing
End Sub
現在,你可以只使用MakeDraggable(Panel1)
或任何其他控件,使其可拖動!
編輯:這兩個示例現在保持控件不被拖出界限。
謝謝 如果你能爲我提供這個樣本,我將不勝感激。 – Ezi 2011-04-06 20:21:57
我意識到保持控制界限是你的主要問題。我修正了這些例子。我檢查控件是否在窗體的clientrectangle中。 – 2011-04-06 20:49:05
它實際上很棒!非常感謝 – Ezi 2011-04-06 21:20:47