dave88
dave88

Reputation: 342

How can I detect if the mouse is being moved to the left or right?

I am trying to detect the left and right mouse movements for a control - like you can use delta for up/down movement. Can anyone help with this? Thanks.

If e.x > 0 Then 'moved right
 msgbox("Moved right!")
else 'moved left
 msgbox("Moved left!")
End If

Upvotes: 0

Views: 2879

Answers (3)

Private firstTime As Boolean = False
Private oldX As Integer

Private Sub Button1_MouseEnter(sender As System.Object, e As System.EventArgs) Handles Button1.MouseEnter
    firstTime = True
End Sub

Private Sub Button1_MouseMove(sender As System.Object, e As System.Windows.Forms.MouseEventArgs) Handles Button1.MouseMove
    If firstTime = True Then
        firstTime = False
    Else
        If e.X > oldX Then
            'moves right
        ElseIf e.X < oldX Then
            'moves left
        End If
    End If

    oldX = e.X
End Sub

Upvotes: 0

Saif Hamed
Saif Hamed

Reputation: 1094

I'm using Timer , and I get a good result

Dim lx As Integer = 0 ' last x position
Dim ly As Integer = 0 ' last y position

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
    Dim x As Integer = MousePosition.X
    Dim y As Integer = MousePosition.Y
    Dim s As String = ""
    If x > lx Then
        s &= "Right,"
    ElseIf x < lx Then
        s &= "Left,"
    ElseIf x = lx Then
        s &= "No Change,"
    End If
    If y > ly Then
        s &= "Down"
    ElseIf y < ly Then
        s &= "Top"
    ElseIf y = ly Then
        s &= "No Change"
    End If
    lx = x
    ly = y
    Label1.Text = s
End Sub

Upvotes: 0

Private oldXY As Point = Point.Empty

Private Sub Form1_MouseMove(sender As Object, 
       e As MouseEventArgs) Handles Me.MouseMove

    If e.X < oldXY.X Then
        ' ....
    ElseIf e.X > oldXY.X Then
        ' ...
    End If
    oldXY.X = e.X
    oldXY.Y = e.Y
End Sub

You will likely want to add a test for Point.Empty so that you dont misreport the first mousemove. Or try to initialize it to Cursor.Position to start with

Upvotes: 1

Related Questions