首先,我想知道鼠标是否在某个区域。 然后,我想检查鼠标是否按住左键。 我想检查只要左按钮关闭,我想跟踪鼠标的位置。 最后,检查左按钮何时释放。
那么,简而言之,我应该从哪里开始跟踪表单中的鼠标事件?
答案 0 :(得分:5)
这是一个用于检测拖动或单击
的简单代码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
答案 1 :(得分:4)
一般来说,当发生鼠标按下事件时,您需要捕获鼠标。然后,即使鼠标离开捕获鼠标的控件区域,您也会收到鼠标移动事件。您可以在鼠标移动事件中计算delta。第一次增量超过系统定义的“拖动区域”时会发生拖动。收到鼠标按下事件后,停止拖动操作。
在Windows窗体中,查看Control类上的MouseDown,MouseMove和MouseUp事件。 MouseEventArgs将包含X / Y坐标。要捕获或释放鼠标,请分别将Capture属性设置为true或false。如果您没有捕获鼠标,那么如果鼠标被释放到控件的边界之外,则不会收到MouseMove或MouseUp事件。
最后,要确定在开始拖动操作之前应允许鼠标移动的最小“距离”,请查看SystemInformation.DragSize属性。
希望这有帮助。
答案 2 :(得分:0)
这样做的唯一方法是通过javascript。
本文将向您解释。 http://luke.breuer.com/tutorial/javascript-drag-and-drop-tutorial.aspx
答案 3 :(得分:0)
可以理解这已经过时了,但我在寻找同样的事情时遇到过这篇文章。我以为可能会有一个实际的拖拽事件,但我猜不是。这是我如何做到的。
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
,因为它会返回相对于整个窗口的位置,而不是表单(或者您正在使用的任何容器)。