How to find Mouse movement direction?

2019-08-01 14:11发布

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条回答
▲ chillily
2楼-- · 2019-08-01 14:56

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.

查看更多
登录 后发表回答