tags:

views:

47

answers:

1

What is the correct way to retrieve a window's position in WPF?

Here's some attempts I made. First attempt, the obvious

Point GetPosition(Window win)
{
    return new Point(win.Top, win.Left);
}

but this returns the "wrong" position when the window is maximized. Second attempt:

Point GetPosition(Window win)
{
    if (win.WindowState == WindowState.Maximized)
        return new Point(0, 0);
    else
        return new Point(win.Top, win.Left);
}

Almost there, but there is still an issue: when you have two (or more) screens and the window is maximized in the second screen you get a (0, 0) position that does not reflect the window's actual position.

I noticed that Window has _actualTop and _actualLeft private members, but no public property to expose them.

How do you retrieve the correct value?

+1  A: 

Yes, awkward. You've got bigger problems, (0, 0) won't be valid even on the primary monitor if the user put the taskbar on the left or the top. Like I did. You can get help from the Windows Forms Screen class. Use its FromPoint() method, then the WorkingArea property. Or the Bounds property if you allow the window to go full-screen.

Personally, I'd just P/Invoke GetWindowRect().

Hans Passant
Thanks Hans, P/Invoking GetWindowRect() actually solves the problem. Not too nice but works as expected. Thanks again!
Francesco De Vittori