Skip to content

Instantly share code, notes, and snippets.

@emoacht
Created April 29, 2022 11:32
Show Gist options
  • Save emoacht/47cf916d9750dc746dbbd2c542e64228 to your computer and use it in GitHub Desktop.
Save emoacht/47cf916d9750dc746dbbd2c542e64228 to your computer and use it in GitHub Desktop.
Get relative position of Popup to its parent.
public static class PopupHelper
{
[DllImport("User32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);
[StructLayout(LayoutKind.Sequential)]
private struct RECT
{
public int Left;
public int Top;
public int Right;
public int Bottom;
public static implicit operator Rect(RECT rect) => new(rect.Left, rect.Top, rect.Right - rect.Left, rect.Bottom - rect.Top);
}
public static Vector GetRelativePositionToParent(Popup popup)
{
if ((PresentationSource.FromVisual(popup.Child) is HwndSource popupSource) &&
GetWindowRect(popupSource.Handle, out RECT popupRect))
{
Point parentPosition = ((Visual)popup.Parent).PointToScreen(new Point(0, 0));
return ((Rect)popupRect).Location - parentPosition;
}
return default;
}
}
@emoacht
Copy link
Author

emoacht commented Apr 29, 2022

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment