Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Popup Control - Find X, Y Coordinates

Tags:

c#

wpf

xaml

popup

I'm trying to get the X,Y coordinates of a popup control. I have tried:

VisualTreeHelper.GetOffset(Popup);

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

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

The CustomPopupPlacementCallback also always returns 0,0 for it's Point parameter.

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

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

Chris Nicol, I have tried your answer with the following code, but still receive 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 Behind:

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));
    }
}
like image 984
gamzu07 Avatar asked Jan 12 '10 20:01

gamzu07


2 Answers

Not sure this is the best way of finding that out, but it does work:

GeneralTransform transform = controlToFind.TransformToAncestor(TopLevelControl);
            Point rootPoint = transform.Transform(new Point(0, 0));
like image 143
Chris Nicol Avatar answered Oct 12 '22 23:10

Chris Nicol


You must 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
    }

for finding X,Y coordinates input this to your code (in rect you have requested coordinates):

        IntPtr handle = (PresentationSource.FromVisual(popup.Child) as HwndSource).Handle;

        RECT rect = new RECT();
        GetWindowRect(handle, out rect);
like image 44
JanSkalicky Avatar answered Oct 12 '22 23:10

JanSkalicky