WPP Popup Control - Find X, Y Coordinates

I am trying to get the X, Y coordinates for a popup menu. I tried:

VisualTreeHelper.GetOffset (Popup);

but the returned vector always contains (0,0) for X and Y.

The parent of the popup is the root of the layout, which is the grid.

CustomPopupPlacementCallback also always returns 0.0 for this Point parameter.

The goal is to allow the user to drag a pop-up window anywhere on the screen. I was going to try to accomplish this by getting the current popup and mouse position, and moving the popup in the same direction of mouse movement.

-------------------- Update --------------------

Chris Nichol, I tried my answer with the following code, but still getting 0.0 for rootPoint:

Xaml:

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="Test.MainWindow" x:Name="Window" Title="MainWindow" Width="800" Height="600"> <Grid x:Name="LayoutRoot"> <Popup x:Name="Popup" IsOpen="True" Placement="Center" Width="100" Height="100"> <Button Click="Button_Click" Content="Test" /> </Popup> </Grid> 

Code for:

 public partial class MainWindow : Window { public MainWindow() { this.InitializeComponent(); // Insert code required on object creation below this point. } private void Button_Click(object sender, RoutedEventArgs e) { GeneralTransform transform = Popup.TransformToAncestor(LayoutRoot); Point rootPoint = transform.Transform(new Point(0, 0)); } } 
+6
c # wpf xaml popup
source share
2 answers

Not sure if this is the best way to find out, but it works:

 GeneralTransform transform = controlToFind.TransformToAncestor(TopLevelControl); Point rootPoint = transform.Transform(new Point(0, 0)); 
+2
source share

You should use win32 api:

add this to your class:

  [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; // X coordinate of topleft point public int Top; // Y coordinate of topleft point public int Right; // X coordinate of bottomright point public int Bottom; // Y coordinate of bottomright point } 

to find the coordinates X, Y enter this into your code (in the request you requested the coordinates):

  IntPtr handle = (PresentationSource.FromVisual(popup.Child) as HwndSource).Handle; RECT rect = new RECT(); GetWindowRect(handle, out rect); 
+2
source share

All Articles