简体   繁体   中英

Set C# Picturebox Container

I am creating a Windows form with PictureBox controls and need to know the location of them relative to the form. I want to change their container to the form, but they must remain on top of the Panel controls they are already in. Is there a way to set the container of the pictureboxes through code?

What are you asking for can be done by setting the control Parent property and then calling BringToFront method.

However changing the parent will also change the treatment of the control location, so in order to keep it in its original location, you need to know the relative location to the form. Which returns you back to the original question.

The relative location of a control to the form can be deteremined by using PointToScreen and PointToClient methods like this:

public static class ControlUtils
{
    public static Point GetFormLocation(this Control control)
    {
        return control.FindForm().PointToClient(control.PointToScreen(control.Location));
    }
}

so you can use

var formLocation = pictureBox.GetFormLocation();

anytime you need to know to know the relative location of your picture boxes to the form.

If that's all you needed, I would suggest you not changing their container. But in case you still want to do that, you can use something like this:

var location = pictureBox.PointToScreen(pictureBox.Location);
pictureBox.Parent = pictureBox.FindForm();
pictureBox.Location = pictureBox.Parent.PointToClient(location);
pictureBox.BringToFront();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM