[英]How can I track mouse click and drag events in VB.NET?
首先,我想知道鼠標是否在某個區域。 然后,我想檢查鼠標是否按住左鍵。 我想檢查只要左按鈕關閉,我想跟蹤鼠標的位置。 最后,檢查左按鈕何時釋放。
那么,簡而言之,我應該從哪里開始跟蹤表單中的鼠標事件?
這是一個用於檢測拖動或單擊的簡單代碼
Public IsDragging As Boolean = False, IsClick As Boolean = False
Public StartPoint, FirstPoint, LastPoint As Point
Private Sub PictureBox1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles picBook.Click
If IsClick = True Then MsgBox("CLick")
End Sub
Private Sub PictureBox1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles picBook.MouseDown
StartPoint = picBook.PointToScreen(New Point(e.X, e.Y))
FirstPoint = StartPoint
IsDragging = True
End Sub
Private Sub PictureBox1_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles picBook.MouseMove
If IsDragging Then
Dim EndPoint As Point = picBook.PointToScreen(New Point(e.X, e.Y))
IsClick = False
picBook.Left += (EndPoint.X - StartPoint.X)
picBook.Top += (EndPoint.Y - StartPoint.Y)
StartPoint = EndPoint
LastPoint = EndPoint
End If
End Sub
Private Sub PictureBox1_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles picBook.MouseUp
IsDragging = False
If LastPoint = StartPoint Then IsClick = True Else IsClick = False
End Sub
一般來說,當發生鼠標按下事件時,您需要捕獲鼠標。 然后,即使鼠標離開捕獲鼠標的控件區域,您也會收到鼠標移動事件。 您可以在鼠標移動事件中計算delta。 第一次增量超過系統定義的“拖動區域”時會發生拖動。 收到鼠標按下事件后,停止拖動操作。
在Windows窗體中,查看Control類上的MouseDown,MouseMove和MouseUp事件。 MouseEventArgs將包含X / Y坐標。 要捕獲或釋放鼠標,請分別將Capture屬性設置為true或false。 如果您沒有捕獲鼠標,那么如果鼠標被釋放到控件的邊界之外,則不會收到MouseMove或MouseUp事件。
最后,要確定在開始拖動操作之前應允許鼠標移動的最小“距離”,請查看SystemInformation.DragSize屬性。
希望這可以幫助。
可以理解這是舊的,但我在尋找同樣的事情時遇到過這篇文章。 我以為可能會有一個實際的拖拽事件,但我猜不是。 這就是我做到的。
Private Sub ContainerToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles ContainerToolStripMenuItem.Click
Dim pnl As New Panel
pnl.Size = New Size(160, 160)
pnl.BackColor = Color.White
AddHandler pnl.MouseDown, AddressOf Control_DragEnter
AddHandler pnl.MouseUp, AddressOf Control_DragLeave
AddHandler pnl.MouseMove, AddressOf Control_Move
Me.Controls.Add(pnl)
End Sub
Private Sub Control_DragEnter(ByVal sender As Object, ByVal e As EventArgs)
MouseDragging = True
End Sub
Private Sub Control_DragLeave(ByVal sender As Object, ByVal e As EventArgs)
MouseDragging = False
End Sub
Private Sub Control_Move(ByVal sender As Object, ByVal e As EventArgs)
If MouseDragging = True Then
sender.Location = Me.PointToClient(Control.MousePosition)
End If
End Sub
ContainerToolStripMenuItem
來自我的ToolStrip,可以即時添加Panel。 MouseDragging
是類級別。 拖拉機就像一個魅力。 另外,不要使用Cursor.Position
,因為它將返回相對於整個Window的位置,而不是Form(或者你所在的任何容器)。
這樣做的唯一方法是通過javascript。
本文將向您解釋。 http://luke.breuer.com/tutorial/javascript-drag-and-drop-tutorial.aspx
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.