【问题标题】:GetWindowRect() not returning a rect [duplicate]GetWindowRect()不返回矩形[重复]
【发布时间】:2015-11-24 01:30:42
【问题描述】:

我有一些看起来像这样的 C# 代码:

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

但是,当我运行此代码时,rect 变量仍然等于 Rect.Zero(顶部/底部/左侧/右侧都为零),即使 GetWindowRect() 返回成功。这个函数调用序列在 C++ 中实现时工作得很好,但在 C# 中通过 P/Invoke 调用时就不行了。

我确定我正确地调用了GetWindowRect();那不是问题。问题是 GetWindowRect() 总是返回 RECT{0,0,0,0},无论我如何更改函数调用或如何定义 P/Invoke。

【问题讨论】:

标签: c# winapi


【解决方案1】:

事实证明,我传递给GetWindowRect() 的句柄不是有效的HWND

【讨论】:

  • 但是你说GetWindowRect返回成功。如果HWND 无效,那么GetWindowRect 应该返回失败。
  • @RaymondChen 我使用类似的代码也遇到了同样的问题。在 C# 中使用 out 会导致程序崩溃,而使用 ref 会产生空引用错误。
  • 原来使用 out 会产生一个双指针。 C#中定义的RECT类需要是结构体而不是类,也可以通过val传递给互操作函数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-08-30
  • 1970-01-01
  • 1970-01-01
  • 2015-11-18
  • 2013-05-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多