crazyGuy
crazyGuy

Reputation: 337

GetWindowRect always returning same values

I know that similar questions have been posted already, but the proposed solutions did not work for me.

I am trying to get a window position in the screen. The only value I really care is the Top-Left point of this window, without the Top-Title bar.

This is the function I am using:

[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GetWindowRect(IntPtr hWnd, ref RECT lpRect);

Where RECT is defined as follow:

    [StructLayout(LayoutKind.Sequential)]
    private struct RECT
    {
        public int Left;
        public int Top;
        public int Right;
        public int Bottom;
    }

So I keep getting always the same values for the window being in different positions of the screen:

Bottom = screen_height
Right = screen_width
Top = -4 // <--
Left = -4 // <--

OS: Windows 7.

App: This is a Surface App (using Surface SDK 2.0)

UPDATE:

After a series of comments, it was suggested to use Spy++ to double check the Window Handle. I then found out that the Handle returned by Spy++ was different from the one I was using. When manually changing the Handle (in Debug mode), I started to get some more reasonable results.

This is how I am getting the Window Handle:

public partial class SurfaceWindow1 : SurfaceWindow
{

    public SurfaceWindow1()
    {
        InitializeComponent();

        IntPtr handle = new WindowInteropHelper(this).Handle;
        ....
    }
}

Any help is appreciated. Thanks

Just to be more informative, here is a picture of what I'd like to get (ignore the keyboard at the bottom):

enter image description here

Upvotes: 1

Views: 1350

Answers (1)

Jim Mischel
Jim Mischel

Reputation: 133950

I think what you're looking for is GetClientRect, which will give you the client rectangle of the window. The left and top values will be (0, 0), but the right and bottom give you the width and the height.

You can then call ClientToScreen, passing the window handle and a point of (0,0). That will give you the screen coordinates of the client area's top-left corner. Just add the width and height (from the previous call to GetClientRect), and you'll have it.

Upvotes: 4

Related Questions