-2

I have a bit of C# code that looks like this:

[DllImport("user32.dll")]
private static extern bool GetWindowRect(IntPtr hWnd, ref Rect rect);
Rect rect = Rect.Zero;
NativeMethods.GetWindowRect(hWnd, ref rect);

However, when I run this code, the rect variable is still equal to Rect.Zero (top/bottom/left/right are all zero), even though GetWindowRect() returned success. This sequence of function calls works just fine when implemented in C++, but not when called in C# through P/Invoke.

I am certain I am calling GetWindowRect() properly; that is not the problem. The problem is that GetWindowRect() is always returning a RECT of {0,0,0,0}, no matter how I change the function call or how I define the P/Invoke.

wjk
  • 1,219
  • 11
  • 27

1 Answers1

0

As it turns out, the handle I was passing into GetWindowRect() was not a valid HWND.

wjk
  • 1,219
  • 11
  • 27
  • 1
    But you said that `GetWindowRect` returned success. If the `HWND` were invalid, then `GetWindowRect` should have returned failure. – Raymond Chen Nov 24 '15 at 06:33
  • @RaymondChen I run into the same issue as well using similar code. Using `out` in C# causes the program to crash, while using `ref` produces a null reference error. – The Muffin Man Nov 07 '17 at 16:35
  • 1
    Turns out using out produces a double pointer. The `RECT` class defined in C# needs to be a struct rather than a class, or you can pass it to the interop function byval. – The Muffin Man Nov 07 '17 at 16:40