使用GetWindowRect碰到的问题

xdq025 2011-08-20 04:06:06

[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
internal static extern bool GetWindowRect(IntPtr hWnd, ref Rect rect);
public class Rect
{
long left;
long top;
long right;
long bottom;
public string ToString()
{
string str = "";
str += "Left:" + left;
str += "Top:" + top;
str += "Right:" + right;
str += "Bottom:" + bottom;
return str;
}
}

private void button1_Click(object sender, EventArgs e)
{
IntPtr handle = Handle;
Rect rect = new Rect();
GetWindowRect(handle, ref rect);
MessageBox.Show(rect.ToString());
}

如在 GetWindowRect的声明中加入ref关键字 则调试时出现错误如下:
运行库遇到了错误。此错误的地址为 0x79f1d57f,在线程 0x9b4 上。错误代码为 0xc0000005。此错误可能是 CLR 中的 bug,或者是用户代码的不安全部分或不可验证部分中的 bug。此 bug 的常见来源包括用户对 COM-interop 或 PInvoke 的封送处理错误,这些错误可能会损坏堆栈。
如果声明时不添加ref如:
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
internal static extern bool GetWindowRect(IntPtr hWnd,Rect rect);
在hWnd有值的时候,不报错,能运行,但获取 rect 为空。


求高手解惑。
...全文
367 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
xdq025 2011-08-20
  • 打赏
  • 举报
回复
灰常的奇怪呀,
怎么复制楼上的代码就成了呢?
rollng 2011-08-20
  • 打赏
  • 举报
回复
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
internal static extern bool GetWindowRect(IntPtr hWnd, ref Rect rect);
public struct Rect
{
int left;
int top;
int right;
int bottom;
public override string ToString()
{
string str = "";
str += "Left:" + left.ToString();
str += "Top:" + top.ToString();
str += "Right:" + right.ToString();
str += "Bottom:" + bottom.ToString();
return str;
}
}

运行成功的
xdq025 2011-08-20
  • 打赏
  • 举报
回复
将class改为struct
long改成int 后 调试
依然出错:
尝试读取或写入受保护的内存。这通常指示其他内存已损坏。
是没有使用marshal类的原因么?
xdq025 2011-08-20
  • 打赏
  • 举报
回复
请问
Marshal
这个怎么加?
为什么要加?
加哪?
xdq025 2011-08-20
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 hdt 的回复:]
long--> int
public class Rect --> struct Rect
rect 加上 Marshal......
[/Quote]
int型不是可以隐式转换成long型,
也就是说long是可以兼容int的啊?
真相重于对错 2011-08-20
  • 打赏
  • 举报
回复
long-->int
public class Rect -->struct Rect
rect 加上 Marshal......

110,534

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧