How to find Mouse movement direction?

2019-08-01 14:15发布

问题:

I need to find out the direction (Left or RIGHT) of a mouse from the moment the mouse is being pressed.

I can use only the event OnMouseMove.

Using the following method I cannot get the direction as e.GetPosition(this).X it is the same value when the mouse move and when it is clicked.

Any idea how to solve it?

    protected override void OnMouseMove(MouseEventArgs e)
    {
        currentPositionX = e.GetPosition(this).X;

        if (e.LeftButton == MouseButtonState.Pressed)
        {
            double deltaDirection = currentPositionX - e.GetPosition(this).X;
            direction = deltaDirection > 0 ? 1 : -1;
        }
    }

回答1:

Your solution is almost complete. You just need to check the current position separately for both cases: when the button is pressed and when it's not:

protected override void OnMouseMove(MouseEventArgs e)
{
    if (e.LeftButton == MouseButtonState.Pressed)
    {
        double deltaDirection = currentPositionX - e.GetPosition(this).X;
        direction = deltaDirection > 0 ? 1 : -1;
        currentPositionX = e.GetPosition(this).X;
    }
    else
    {
        currentPositionX = e.GetPosition(this).X;
    }
}

Moving to the right will result in -1 and moving to the left returns 1.