C#Mouse PreMove事件?

时间:2012-07-21 17:31:40

标签: c# winforms winforms-interop

有人能告诉我是否存在一个带有eventargs的事件MousePreMove,它告诉我游标的移动方向?

我找到了一个Win API来阻止任何用户输入,但它不是我想要的。

2 个答案:

答案 0 :(得分:2)

不,没有MousePreMove事件,但您可以自己编写一些内容来获取光标的方向。例如:

public partial class Form1 : Form {

    Point cursorPosition;
    Direction cursorDirection, previousCursorPosition;

    public event EventHandler<MouseDirectionEventArgs> DirectionChanged;

    public Form1( ) {
        InitializeComponent( );
        cursorPosition = PointToClient( Cursor.Position );

        DirectionChanged += new EventHandler<MouseDirectionEventArgs>( Form1_DirectionChanged );
    }

    void Form1_DirectionChanged( object sender, MouseDirectionEventArgs e ) {
        MessageBox.Show( e.MouseDirection.ToString( ) );
    }

    protected override void OnMouseMove( MouseEventArgs e ) {

        if ( e.X > cursorPosition.X && e.Y > cursorPosition.Y )
            cursorDirection = Direction.RightDown;
        else if ( e.X > cursorPosition.X && e.Y < cursorPosition.Y )
            cursorDirection = Direction.RightUp;
        else if ( e.X < cursorPosition.X && e.Y > cursorPosition.Y )
            cursorDirection = Direction.LeftDown;
        else if ( e.X < cursorPosition.X && e.Y < cursorPosition.Y )
            cursorDirection = Direction.LeftUp;

        OnDirectionChanged(new MouseDirectionEventArgs( cursorDirection ) );

        previousCursorPosition = new Point(cursorPosition.X, cursorPosition.Y);
        cursorPosition = e.Location;

        base.OnMouseMove( e );
    }

    protected virtual void OnDirectionChanged(MouseDirectionEventArgs e){
        if ( DirectionChanged != null )
            DirectionChanged( this, e );
    }
}

enum Direction {
    LeftUp,
    LeftDown,
    RightUp,
    RightDown
}

class MouseDirectionEventArgs : EventArgs {
    public readonly Direction MouseDirection {
        get;
        set;
    }

    public MouseDirectionEventArgs( Direction direction ) {
        MouseDirection = direction;
    }
}

这是一个简单的程序,显示鼠标方向与前一个鼠标位置的比较。

修改

如果你想阻止鼠标朝你想要的方向移动:

void Form1_DirectionChanged( object sender, MouseDirectionEventArgs e ) {
     if(e.MouseDirtection == Direction.LeftUp) //example
        Cursor.Position = PointToScreen( previousCursorPosition );
}

答案 1 :(得分:0)

我真的不明白你为什么要阻止鼠标移动。这将产生的一个重要问题是您的用户无法移动鼠标(显然)。因此,当您在用户使用程序时实施此操作时,他们将无法单击“开始”菜单。

然而,由于这是你的目标,你可以通过改变你的想法从'停止鼠标移动'到'如果鼠标不在我想要的地方,把它放在我做的地方'来更好地服务。

所以,根据Fuex的代码使用OnMouseMove事件,类似这样的东西(这只是伪代码)

cursorPosition = e.Location;

if(cursorPosition!= alowedArea) {     cursorPosition = preciousCursorPostion; }

preciousCursorPostion = cursorPosition;

e.Location = cursorPosition;