I am creating an application in which I can move the Labels
that are on a PictureBox
.
The problem is that I want these to only Labels move
The PictureBox
control is not a container, you can't directly put another control inside it, as you would do with a Panel
, a GroupBox
or other controls that implement IContainerControl.
You could parent the Label
(in this case), setting the Label
Parent to a PictureBox
handle. The Label.Bounds
will then reflect the parent Bounds
.
However it's not necessary: you can just calculate the position of the Label in relation to the control that contains both (Label
(s) and PictureBox
):
You can restrict the movements of other Label
controls subscribing to the MovableLabel_MouseDown/MouseUp/MouseMove
events.
An example:
bool ThisLabelCanMove;
Point LabelMousePosition = Point.Empty;
private void MovableLabel_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
LabelMousePosition = e.Location;
ThisLabelCanMove = true;
}
}
private void MovableLabel_MouseUp(object sender, MouseEventArgs e)
{
ThisLabelCanMove = false;
}
private void MovableLabel_MouseMove(object sender, MouseEventArgs e)
{
if (ThisLabelCanMove)
{
Label label = sender as Label;
Point LabelNewLocation = new Point(label.Left + (e.Location.X - LabelMousePosition.X),
label.Top + (e.Location.Y - LabelMousePosition.Y));
LabelNewLocation.X = (LabelNewLocation.X < pictureBox1.Left) ? pictureBox1.Left : LabelNewLocation.X;
LabelNewLocation.Y = (LabelNewLocation.Y < pictureBox1.Top) ? pictureBox1.Top : LabelNewLocation.Y;
LabelNewLocation.X = (LabelNewLocation.X + label.Width > pictureBox1.Right) ? label.Left : LabelNewLocation.X;
LabelNewLocation.Y = (LabelNewLocation.Y + label.Height > pictureBox1.Bottom) ? label.Top : LabelNewLocation.Y;
label.Location = LabelNewLocation;
}
}