[英]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. 我正在使用PictureBox
控件创建Windows窗体,并且需要知道它们相对于窗体的位置。 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? 我想将它们的容器更改为窗体,但是它们必须保留在它们已经位于的Panel
控件的顶部。是否可以通过代码设置图片框的容器?
What are you asking for can be done by setting the control Parent
property and then calling BringToFront
method. 您可以通过设置控件的Parent
属性然后调用BringToFront
方法来完成您的要求。
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: 可以使用如下所示的PointToScreen
和PointToClient
方法来确定控件相对于窗体的相对位置:
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.