2011-01-12 343 views
4

首先,我想知道鼠標是否在某個區域。 然後,我想檢查鼠標是否保持左鍵單擊。 只要左側按鈕關閉,我想檢查,並且我想跟蹤鼠標的位置。 最後,檢查左鍵何時被釋放。如何在VB.NET中跟蹤鼠標點擊和拖動事件?

因此,總之,我應該從哪裏開始跟蹤我的表單中的鼠標事件?

回答

4

一般來說,當鼠標停止事件發生時,您需要捕獲鼠標。然後,即使鼠標離開捕獲鼠標的控件區域,您也會收到鼠標移動事件。您可以在鼠標移動事件中計算增量值。第一次增量超過系統定義的「拖拽區域」時會發生拖拽。當收到鼠標向上事件時,停止拖動操作。

在Windows窗體中,查看Control類上的MouseDown,MouseMove和MouseUp事件。 MouseEventArgs將包含X/Y座標。要捕獲或釋放鼠標,分別將Capture屬性設置爲true或false。如果您沒有捕獲鼠標,那麼如果鼠標在控件邊界外釋放,您將不會收到MouseMove或MouseUp事件。

最後,要確定鼠標在開始拖動操作前應允許移動的最小「距離」,請查看SystemInformation.DragSize屬性。

希望這會有所幫助。

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 
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,增加了對即時的面板。 MouseDragging是班級。像魅力一樣拖曳。此外,不要使用Cursor.Position,因爲它會返回相對於您整個窗口的位置,而不是表單(或您所在的任何容器)。