检查所有鼠标按钮的按钮状态

时间:2011-02-13 15:57:14

标签: c# .net wpf events coding-style

是否有更好的方法来检查所有鼠标按钮的按钮状态,而不是检查是否有额外的按钮?

var mouseEventArgs = (System.Windows.Input.MouseEventArgs)e.StagingItem.Input;

if (mouseEventArgs.LeftButton == MouseButtonState.Released &&
    mouseEventArgs.MiddleButton == MouseButtonState.Released &&
    mouseEventArgs.RightButton == MouseButtonState.Released &&
    mouseEventArgs.XButton1 == MouseButtonState.Released &&
    mouseEventArgs.XButton2 == MouseButtonState.Released)
{
    return;
}

如果没有,我怎么能在不重复自己的情况下更优雅呢?

提前致谢!

2 个答案:

答案 0 :(得分:7)

我认为除了将其重构为方法之外,你还有很多工作要做,因为所有按钮都没有预定义的集合。如果您希望它完全看不见,您可以使用这样的扩展方法:

public static class Extensions
{
    public static bool CheckUniformButtonState(this MouseButtonEventArgs e, MouseButtonState state)
    {
        switch (state)
        {
            case MouseButtonState.Pressed:
                return (e.LeftButton == MouseButtonState.Pressed &&
                    e.RightButton == MouseButtonState.Pressed &&
                    e.MiddleButton == MouseButtonState.Pressed &&
                    e.XButton1 == MouseButtonState.Pressed &&
                    e.XButton2 == MouseButtonState.Pressed);
            case MouseButtonState.Released:
                return (e.LeftButton == MouseButtonState.Released &&
                    e.RightButton == MouseButtonState.Released &&
                    e.MiddleButton == MouseButtonState.Released &&
                    e.XButton1 == MouseButtonState.Released &&
                    e.XButton2 == MouseButtonState.Released);
            default:
                return false;
        }
    }
}

(并不是所有人都会检查是否按下所有5个按钮..)

然后你可以这样检查:

if (mouseEventArgs.CheckUniformButtonState(MouseButtonState.Released))
{
    return;
}

答案 1 :(得分:2)

var buttonStates = new [] {
     mouseEventArgs.LeftButton, 
     mouseEventArgs.MiddleButton,
     mouseEventArgs.RightButton,
     mouseEventArgs.XButton1,
     mouseEventArgs.XButton2};

if (buttonStates.All(s => s == MouseButtonState.Released))
{
     return;
}