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.
The
LeftandRightproperties are relative to the parent container, whileControl.MousePositionis relative to the screen. The PointToClient method helps you converting screen coordinated to relative coordinates: