繁体   English   中英

GetWindowRect 为左右返回相同的值

[英]GetWindowRect returning same value for left & right

我正在尝试捕获浏览器屏幕截图,而我的 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);
    }

您没有检查您的 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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM