Akinni
Akinni

Reputation: 67

Set C# Picturebox Container

I am creating a Windows form with PictureBoxcontrols 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?

Upvotes: 0

Views: 1339

Answers (1)

Ivan Stoev
Ivan Stoev

Reputation: 205539

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();

Upvotes: 1

Related Questions