KairisCharm
KairisCharm

Reputation: 1373

Windows Forms unusual mouse manipulation

I have a Windows Form in which I'm rendering a map that I can zoom in and out of. I have it set so that if you hold the left mouse button, it pans across the map, and if you use the mouse wheel, it zooms in and out on the spot where the mouse cursor currently points. But some of my user base uses Mac hardware, and may not have a mouse with a wheel. I want to be able to hold the right mouse button and move the mouse forward and backward to zoom in and out, but to do this, I need to lock the cursor in place while the right mouse button is clicked. Any thoughts on how to do this?

I've tried Cursor.Position = Point(...) but that doesn't work immediately and causes some bizarre behavior.

Upvotes: 1

Views: 107

Answers (2)

Shell
Shell

Reputation: 6849

I don't know why setting the Cursor.Position method doesn't work in your case. I have taken a simple windows form without placing any controls I have overided following methods and set the Cursor.Position property OnMouseMove method. Its working.

Just paste the following code in your form and run it.

    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);
    }

Upvotes: 0

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73502

I recommend you to Hide the cursor on MouseDown, then Show it in MouseUp. Till then you can draw the cursor manually if you want to show it.

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));
    }
}

Upvotes: 2

Related Questions