【问题标题】:GetWindowRect returning same value for left & rightGetWindowRect 为左右返回相同的值
【发布时间】:2011-05-28 15:17:57
【问题描述】:

我正在尝试捕获浏览器屏幕截图,我的 Win32 api 方法之一是 GetWindowRect。这将返回相同的左右值。只有当我在以 Win7 作为操作系统的远程计算机上运行我的应用程序时才会发生这种情况。

我的 PrintWindow 方法在这台机器上也失败了。如果有人之前遇到过这个问题,请告诉我。

以上两种方法都适用于远程机器上的 Vista 和 XP 作为操作系统。

添加一些我的应用程序的方法。

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

【问题讨论】:

  • 有代码要分享?如果在建立远程桌面会话后重新启动应用程序,它会起作用吗?
  • 这段代码是运行在浏览器进程还是其他地方?您从哪里获得 HWND?

标签: c# windows winapi


【解决方案1】:

您没有检查您的 Win32 返回码。我的猜测是 GetWindowRect 由于某种原因失败,因此没有为矩形分配任何值。因此它的值保持未初始化。

检查返回值,如果调用失败,请使用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();

【讨论】:

  • 抱歉回复晚了。我检查了 Win32 返回码和 Marshal.GetLastWin32Error() 返回 0。这里有一些关于这个问题的更新。我正在尝试在 IE 和 Chrome 中捕获屏幕截图。在 IE 中运行时,它在 Bitmap bm = new Bitmap(windowSize.Width, windowSize.Height) 行中失败,宽度和高度为 0。但是在 Chrome 中运行时,它得到了正确的高度和宽度,但在 PrintWindow 步骤中失败了。在这两种情况下,Win32 返回错误代码都是 0。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多