【发布时间】:2016-02-19 17:18:25
【问题描述】:
我希望有人能帮我解决这个问题,我的应用程序中有以下代码,可以让我获得一个 Rect
var windowPosition = NativeMethods.GetWindowRect(this._hwnd);
return new Rect(windowPosition.Left, windowPosition.Top, windowPosition.Width, windowPosition.Height);
我在为自定义窗口编写的一些代码中使用它,这是在 WPF 应用程序中,使用 IWindowManager.OpenWindow 打开窗口。
当我运行代码并打开窗口时,我在 windowPosition 对象中获得以下值,这是一个 RECT
top = 1466, bottom = 785, left = 26, right = 26, width = 0, height = -681
我看不出代码中有什么问题最终会在 RECT 中出现这些奇数值,因此我在下一行中得到一个 ArgumentException。
我也尝试将此窗口作为主应用程序窗口运行,但我遇到了同样的问题,该应用程序正在使用 MVVM 和 Caliburn Micro,尽管我不确定为什么会有所不同。
根据要求,RECT 结构定义如下:
[StructLayout(LayoutKind.Sequential)]
internal struct RECT
{
public void Offset(int dx, int dy)
{
this.Left += dx;
this.Top += dy;
this.Right += dx;
this.Bottom += dy;
}
public int Left { get; set; }
public int Top { get; set; }
public int Right { get; set; }
public int Bottom { get; set; }
public int Width
{
get
{
return this.Right - this.Left;
}
}
public int Height
{
get
{
return this.Bottom - this.Top;
}
}
public POINT Position
{
get
{
return new POINT { x = this.Left, y = this.Top };
}
}
public SIZE Size
{
get
{
return new SIZE { cx = this.Width, cy = this.Height };
}
}
}
还有来自 NativeMethods 的 GetWindowRect 方法:
[DllImport("user32.dll", EntryPoint = "GetWindowRect", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GetWindowRectInternal(IntPtr hWnd, out RECT lpRect);
public static RECT GetWindowRect(IntPtr hwnd)
{
RECT rc;
if (!GetWindowRectInternal(hwnd, out rc))
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
return rc;
}
我正在使用 WindowInteropHelper(window).Handle 访问 hWnd,我忽略了包含来自 NativeMethods 的公共方法,现在已经包含了,为浪费时间道歉。
【问题讨论】:
-
RECT 没有宽度或高度属性,显着增加了您刚刚声明错误的几率。奇怪你没有发布相关代码。
-
向我们展示您如何定义 GetWindowRect 和您的 RECT 结构。
-
它是 let-top-right-bottom,而不是 left-right-top-bottom。
-
今晚我会改变它并试一试,但为什么会有不同呢?
-
您发布了伪造的代码。这是对时间的巨大浪费。请发帖minimal reproducible example。