My code does not return the proper coordinates for the cursor

45 Views Asked by At

I am trying to write a program that needs to move a picture box to the coordinates of the cursor on a mouse down event in windows forms app C#.

private void MouseClick(object sender, MouseEventArgs e)
        {
            //left mouse button pressed 
            if (e.Button == MouseButtons.Left)
            {
                //gets the coords of the mouse
                MX = Control.MousePosition.X; 
                MY = Control.MousePosition.Y;
                //moves the picture box to these coords
                HitSlash.Left = MX;
                HitSlash.Top = MY;
                //shows the object, default hidden
                HitSlash.Show();
            }
        }

the program works however the picture box is always placed far down to the bottom right of the cursor. when i restart the program the picture box always has a different offset and cannot be fixed by manually changing the values of the coordinates.

1

There are 1 best solutions below

0
Klaus Gütter On

The Left and Right properties are relative to the parent container, while Control.MousePosition is relative to the screen. The PointToClient method helps you converting screen coordinated to relative coordinates:

var mousePos = Control.MousePosition;
var coords = HitSlash.Parent.PointToClient(mousePos);
HitSlash.Left = coords.X;
HitSlash.Top = coords.Y;