Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I track mouse click and drag events in VB.NET?

First, I want to know if the mouse is in some area. Then, I want to check if the mouse holds the left click. I want to check as long as the left button is down, and I want to track the mouse's position. And finally, check when the left button is released.

So, in short, where should I start for tracking mouse events in my form?

like image 432
Voldemort Avatar asked Jan 12 '11 05:01

Voldemort


2 Answers

Generally speaking, when the mouse down event occurs, you would need to capture the mouse. Then you will receive mouse move events even if the mouse leaves the area of the control that has captured the mouse. You can calculate delta's in the mouse move events. A drag would occur the first time the delta exceeds a system-defined "drag area". When the mouse up event is received, stop the drag operation.

In Windows Forms, look at the MouseDown, MouseMove, and MouseUp events on the Control class. The MouseEventArgs will contain the X/Y coordinates. To capture or release the mouse, set the Capture property to true or false respectively. If you do not capture the mouse, then you will not receive the MouseMove or MouseUp events if the mouse is released outside of the bounds of the control.

Finally, to determine the minimum "distance" the mouse should be allowed to move before starting the drag operation, look at the SystemInformation.DragSize property.

Hope this helps.

like image 137
Josh Avatar answered Oct 13 '22 12:10

Josh


This is a simple code for detect Drag or Click

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
like image 24
Mohsen Noori Avatar answered Oct 13 '22 12:10

Mohsen Noori