Windows 形成异常的鼠标操作

Windows Forms unusual mouse manipulation

我有一个 Windows 表单,我在其中渲染可以放大和缩小的地图。我将其设置为如果您按住鼠标左键,它会在地图上平移,如果您使用鼠标滚轮,它会在鼠标光标当前指向的位置放大和缩小。但是我的一些用户群使用 Mac 硬件,并且可能没有带滚轮的鼠标。我希望能够按住鼠标右键并前后移动鼠标以放大和缩小,但为此,我需要在单击鼠标右键时将光标锁定到位。关于如何做到这一点有什么想法吗?

我试过 Cursor.Position = Point(...) 但这不会立即起作用并导致一些奇怪的行为。

我建议你 Hide 光标在 MouseDown 上,然后 Show 它在 MouseUp 上。到此为止,如果你想显示它,你可以手动绘制光标。

private Point? downPoint;
protected override void OnMouseDown(MouseEventArgs e)
{
    downPoint = this.PointToClient(MousePosition);
    Cursor.Hide();

    base.OnMouseDown(e);
}

protected override void OnMouseUp(MouseEventArgs e)
{
    if (downPoint.HasValue)
    {
        Cursor.Show();
    }
    downPoint = null;

    base.OnMouseUp(e);
}

protected override void OnPaint(PaintEventArgs e)
{
    base.OnPaint(e);

    if (downPoint.HasValue)
    {
        Cursor.Draw(e.Graphics, new Rectangle(downPoint.Value, Cursor.Size));
    }
}

我不知道为什么设置 Cursor.Position 方法对你的情况不起作用。我采用了一个简单的 windows 表单,没有放置任何控件 我已经覆盖了以下方法并设置了 Cursor.Position 属性 OnMouseMove 方法。它的工作。

只需将以下代码粘贴到您的表单中并运行它。

    Point p = Point.Empty;
    protected override void OnMouseDown(MouseEventArgs e)
    {
        p = this.PointToScreen(e.Location);
        base.OnMouseDown(e);
    }

    protected override void OnMouseUp(MouseEventArgs e)
    {
        p = Point.Empty;
        base.OnMouseUp(e);
    }

    protected override void OnMouseMove(MouseEventArgs e)
    {
        if (p != Point.Empty)
            Cursor.Position = p;
        base.OnMouseMove(e);
    }