如何解决GetWindowRect为左和右返回相同的值
| 我正在尝试捕获浏览器屏幕截图,我的Win32 api方法之一是GetWindowRect。这将返回相同的左和右值。仅当我在以Win7作为操作系统的远程计算机上运行应用程序时,才会发生这种情况。 我的PrintWindow方法在这台机器上也失败了。如果之前有人遇到过此问题,请告诉我。 以上两种方法在Vista和XP作为远程计算机上的OS时都可以正常工作。 添加我的应用程序的几种方法。 [DllImport(\"user32.dll\")]
public static extern bool PrintWindow(IntPtr hwnd,IntPtr hdcBlt,uint nFlags);
[DllImport(\"user32.dll\")]
public static extern bool GetWindowRect(IntPtr hwnd,ref Rect rectangle);
private Image Capture(IntPtr hwnd)
{
Rectangle windowSize = this.GetWindowPosition(hwnd);
Bitmap bm = new Bitmap(windowSize.Width,windowSize.Height);
using (Graphics g = Graphics.FromImage(bm))
{
IntPtr hdc = g.GetHdc();
if (PrintWindow(hwnd,hdc,0) == false)
{
throw new Exception(\"PrintWindow call failed\");
}
g.ReleaseHdc(hdc);
g.Flush();
}
return bm;
}
private Rectangle GetWindowPosition(IntPtr hwnd)
{
Rect r = new Rect();
GetWindowRect(hwnd,ref r);
return new Rectangle(r.Left,r.Top,r.Width,r.Height);
}
解决方法
您没有检查Win32返回码。我的猜测是
GetWindowRect
由于某种原因而失败,因此不会为rect分配任何值。因此,其值保持未初始化。
检查返回值,如果调用失败,请使用Marshal.GetLastWin32Error()
找出原因。您还需要更新您的P / Invokes:
[DllImport(\"user32.dll\",SetLastError=true)]
public static extern bool PrintWindow(IntPtr hwnd,IntPtr hdcBlt,uint nFlags);
[DllImport(\"user32.dll\",SetLastError=true)]
public static extern bool GetWindowRect(IntPtr hwnd,ref Rect rectangle);
...
if (!GetWindowRect(hwnd,ref r))
int ErrorCode = Marshal.GetLastWin32Error();
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。