1

I would like to get cursor position on form.

Code below works, but not when cursor is positioned over some pictureBox(s).

So I need some help on this.

Thank you !

protected override void OnMouseMove(MouseEventArgs e)
{
    base.OnMouseMove(e);

    Point p = Cursor.Position;

    label1.Text = "x= " + p.X.ToString();
    label2.Text = "y= " + p.Y.ToString();
}
mesko
  • 13
  • 3

3 Answers3

1

You have to subscribe to MouseMove event of that picture box and call your method in it.

// in Form1.cs

private void PictureBox1_MouseMove(object sender, MouseEventArgs e)
{
    OnMouseMove(e);
}

Or you can override form's CreateControlsInstance method to return custom control collection which will subscribe to every child control's MouseMove event

// in Form1.cs

protected override void OnMouseMove(MouseEventArgs e)
{
    base.OnMouseMove(e);

    Point p = Cursor.Position;

    label1.Text = "x= " + p.X.ToString();
    label2.Text = "y= " + p.Y.ToString();
}

class Form1ControlCollection : ControlCollection
{
    Form1 owner;
    internal Form1ControlCollection(Form1 owner) : base(owner)
    {
        this.owner = owner;
    }

    public override void Add(Control value)
    {
        base.Add(value);
        value.MouseMove += Value_MouseMove;
    }

    private void Value_MouseMove(object sender, MouseEventArgs e)
    {
        owner.OnMouseMove(e);
    }
}

protected override Control.ControlCollection CreateControlsInstance()
{
    return new Form1ControlCollection(this);
}

Add this snippet into your form

DotNet Developer
  • 2,973
  • 1
  • 15
  • 24
0

I guess it's because you are overriding only the OnMouseMove - Method of your Form. To capture the mouse move event in your picture box (or any control) use the MouseMove - Event from the control.

private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
    Point p = Cursor.Position;

    label1.Text = "x= " + p.X.ToString();
    label2.Text = "y= " + p.Y.ToString();
}
mitch
  • 115
  • 3
  • 8
0

Thank you guys !

This works for me.

In protected override void OnMouseMove(MouseEventArgs e) you can use both comment or uncomment code

private void PictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        OnMouseMove(e);
    }

    private void pictureBox2_MouseMove(object sender, MouseEventArgs e)
    {
        OnMouseMove(e);
    }

    protected override void OnMouseMove(MouseEventArgs e)
    {
        //base.OnMouseMove(e);

        //Point p = Cursor.Position;

        //label1.Text = "x= " + p.X.ToString();
        //label2.Text = "y= " + p.Y.ToString();

        label1.Text = "x= " + e.X.ToString();
        label2.Text = "y= " + e.Y.ToString();        
    }
mesko
  • 13
  • 3