How to find Mouse movement direction?

試著忘記壹切 提交于 2020-01-05 23:18: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:


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.



来源:https://stackoverflow.com/questions/23865345/how-to-find-mouse-movement-direction

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!