GetWindowRect returns NullReferenceException

GetWindowRect returns NullReferenceException

我正在尝试获取附加到 javaw.exe 进程的某个 window 的大小和位置。

遗憾的是,GetWindowRect 抛出一个错误:"NullReferenceException" - 我已经检查过,none 它的参数 == null。

这是一段代码

调用示例:

    [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;
    }

运行 附加进程的静态函数:

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

用法示例:

    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 };
    }

在此先感谢,如果涉及到本机函数的使用,我完全没有经验。

您将结构声明为 C# class。那已经是引用类型了。因此,当您将它作为输出参数传递时,您现在有一个双指针。要么

  • 从 class 更改为结构,
  • 或按值传递 class。