Search code examples
c#functionpinvokenative

GetWindowRect returns NullReferenceException


I'm trying to get size and position of a certain window attached to javaw.exe process.

Sadly, GetWindowRect throws an error: "NullReferenceException" - and I've checked, none of it's arguments == null.

Here's the piece of code

Invoking sample:

    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool GetWindowRect(IntPtr handle, out WindowRect rect);
    [StructLayout(LayoutKind.Sequential)]
    private class WindowRect
    {
        public int Left;
        public int Top;
        public int Right;
        public int Bottom;
    }

Running static function to attach process:

NB.Attach( Process.GetProcessesByName("javaw")[0] );

Usage sample:

    public static void Attach( Process process )
    {
        FocusProcess = process;
        FocusWindow = FindWindow(null, process.MainWindowTitle);
    }

    public static int[] GetWindowPosition()
    {
        WindowRect rect = new WindowRect();

        Console.WriteLine(FocusProcess == null);
        Console.WriteLine(FocusProcess.MainWindowHandle == null);
        Console.WriteLine(rect==null);
        GetWindowRect(FocusProcess.MainWindowHandle, out rect);
        if ( rect.Top != 0 )
        {
            return new int[] { rect.Left, rect.Top };
        }
        return new int[] { 0, 0 };
    }

Thanks in advance, I'm totally inexperienced if it comes to usage of native functions.


Solution

  • You declared the struct as a C# class. That's a reference type already. So when you pass it as an out param you now have a double pointer. Either

    • Change from class to struct,
    • or pass the class by value.