Don't move the Labels outside a PictureBox

后端 未结 2 1854
走了就别回头了
走了就别回头了 2020-12-22 04:15

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

2条回答
  •  粉色の甜心
    2020-12-22 04:50

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

提交回复
热议问题