Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
184 views
in Technique[技术] by (71.8m points)

c# - Recover previous absolute position for PictureBox when Parent is changed?

In my GUI, i need to change Parents of PictureBoxes to the background PictureBox so that the transparency works correctly.

However, changing the parent also changes the location of the pictureboxes. I have tried grabbing the absolute location of the picture box via the PointToClient, but it doesn't work. I put the coordinates in the comments, and they don't change after assigning the new parent even though the image visibly changes location. Furthermore, I don't expect that it could possibly work as it's being passed a point, not an object with more information about parents and whatnot that's needed to deduce the absolute position.

What is the correct way to deduce the absolute position of an element so that I can move the image to the correct location after its parent changes? Or is there a better way to do this?

Point oldRel = pictureBox4.Location; //258, 109
Point oldAbs = PointToClient(oldRel); //75, -96
//Commenting out this line fixes the image shift but ruins the transparency
pictureBox4.Parent = pictureBox2;  
Point newRel = pictureBox4.Location; //258, 109
Point newAbs = PointToClient(pictureBox4.Location); //75, -96
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This will move a Control child from one Parent to a new one, keeping the absolute screen position intact:

void MoveTo(Control child, Control newParent )
{
    child.Location = newParent.PointToClient(child.PointToScreen(Point.Empty));
    child.Parent = newParent;
}

The trick with PointToClient and PointToScreen is to use them from the right parent control; not setting the control will default to the Form, which will miss out on the actual position of the parent..


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...