2

I know this has been asked before (Get Absolute Position of element within the window in wpf) but I haven't been able to implement properly yet. I'm trying to have a child window open up relative to the control in the parent window. So far, I have this;

messageWindow = new Message(true);
Point relativePoint = btn1.TransformToAncestor(this).Transform(new Point(0, 0));
messageWindow.Left = relativePoint.X;
messageWindow.Top = relativePoint.Y;
messageWindow.Show();

Now although this does effect the position of the child window (messageWindow), it doesn't seem to place it on/beside the btn1 control in the parent. Another problem I have with it is that if I move the parent window, then recall this method having closed the original messageWindow the new instance of the window displays in the old position (even though btn1 is in a new position). I find this odd and was wondering if anyone could help me fix this.

UPDATE

Thanks to Charleh for explaining that I was only setting them relative to the control location in the window, not to the overall screen. So now it is a question of getting the parent window's location on the screen and adding it to the XY also. How would I get this? Just tried this code (although I'll be honest, I don't quite understand it) bus still doesn't seem to follow very closely. What's a good way of getting Window location on the screen?;

messageWindow= new Message(true);
Point relativePoint = btn1.TransformToAncestor(this).Transform(new Point(0, 0));
PresentationSource ScreenPos = PresentationSource.FromVisual(this);

messageWindow.Left = relativePoint.X + (96.0 * ScreenPos.CompositionTarget.TransformToDevice.M11);
messageWindow.Top = relativePoint.Y + (96.0 * ScreenPos.CompositionTarget.TransformToDevice.M22);
messageWindow.Show();
Community
  • 1
  • 1
windowsgm
  • 1,566
  • 4
  • 23
  • 55
  • 1
    Are you taking into account the coordinates of the parent window? This only gives you the relative position for the child window - not the absolute position, it sounds like you need to place the child window at the same position as the parent window, then transform it using relativePoint – Charleh Jun 27 '12 at 14:01
  • @Charleh Oh ya. That makes sense why it didn't move with the parent. Thanks! – windowsgm Jun 27 '12 at 14:10

1 Answers1

3

relativePoint is the position of the control relative to the Window, not the screen. When setting the Left and Right points of messageWindow (the child window), the points are relative to the screen, not the parent window.

In order to get the correct position, you'll need to find the position of the parent window and then do some math to find where the control is located relative to the screen, not the window which should give you the location of where you want to place the child window.

Metro Smurf
  • 37,266
  • 20
  • 108
  • 140