如何在VB.NET中跟踪鼠标点击和拖动事件?

问题描述:

首先,我想知道鼠标是否在某个区域。 然后,我想检查鼠标是否保持左键单击。 只要左侧按钮关闭,我想检查,并且我想跟踪鼠标的位置。 最后,检查左键何时被释放。如何在VB.NET中跟踪鼠标点击和拖动事件?

因此,总之,我应该从哪里开始跟踪我的表单中的鼠标事件?

一般来说,当鼠标停止事件发生时,您需要捕获鼠标。然后,即使鼠标离开捕获鼠标的控件区域,您也会收到鼠标移动事件。您可以在鼠标移动事件中计算增量值。第一次增量超过系统定义的“拖拽区域”时会发生拖拽。当收到鼠标向上事件时,停止拖动操作。

在Windows窗体中,查看Control类上的MouseDown,MouseMove和MouseUp事件。 MouseEventArgs将包含X/Y坐标。要捕获或释放鼠标,分别将Capture属性设置为true或false。如果您没有捕获鼠标,那么如果鼠标在控件边界外释放,您将不会收到MouseMove或MouseUp事件。

最后,要确定鼠标在开始拖动操作前应允许移动的最小“距离”,请查看SystemInformation.DragSize属性。

希望这会有所帮助。

要做到这一点的唯一方法是通过javascript。

本文将向您解释。 http://luke.breuer.com/tutorial/javascript-drag-and-drop-tutorial.aspx

+4

当然,OP可能已经清楚了他正在使用的内容,但我不认为他正在尝试在HTML中执行此操作。 – Josh 2011-01-12 05:37:02

这是一个简单的代码进行检测拖动或点击

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 

可以理解的,这是老了,但我碰到这个帖子跑而希望做同样的事情。我想可能会有一个实际的拖延事件,但我猜不是。这是我做到的。

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,增加了对即时的面板。 MouseDragging是班级。像魅力一样拖曳。此外,不要使用Cursor.Position,因为它会返回相对于您整个窗口的位置,而不是表单(或您所在的任何容器)。