PrintWindow返回null数据,Works in C ++

时间:2013-04-06 21:56:13

标签: c# screen-capture printscreen

我已经成功地使用PrintWindow在C ++中工作,但是当我尝试在C#中执行时,我得到了一个带有空数据的位图。在.NET 4.0上使用VS 2012 Pro。这是我的代码:

    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);

    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    public static extern bool PrintWindow(IntPtr hWnd, IntPtr hdcBlt, int nFlags);

    [DllImport("user32.dll")]
    public static extern ushort getLastError();

    static int count = 0;
    public Bitmap getWindow(IntPtr windowHandle)
    {
        RECT rect;
        Window.GetWindowRect(windowHandle, out rect);

        Console.WriteLine(rect.X);
        Console.WriteLine(rect.Y);
        Console.WriteLine(rect.Width);
        Console.WriteLine(rect.Height);
        Console.WriteLine();

        Bitmap bmp = new Bitmap(rect.Width, rect.Height);
        Graphics gfxBmp = Graphics.FromImage(bmp);
        IntPtr hdcBitmap = gfxBmp.GetHdc();

        bool success = PrintWindow(windowHandle, hdcBitmap, 0);
        if (!success)
        {
            Console.WriteLine("Error copying image");
            Console.WriteLine(getLastError());
        }

        bmp.Save("image_" + count++ + ".bmp");

        gfxBmp.ReleaseHdc(hdcBitmap);
        gfxBmp.Dispose();

        return bmp;

    }

这是输出:

182
182
664
533

没有打印错误消息,看起来句柄有效,因为RECT边界是正确的。 Following this example我使用计算器程序在C ++中使用它,但使用计算器的相同代码在C#中不起作用。

我需要它在C#中工作。

1 个答案:

答案 0 :(得分:2)

根据要求:-) 尝试在PrintWinow()调用之后直接放置ReleaseHdc。

See here.

我必须猜测原因,但它可能类似“只要HDC被非托管代码锁定,托管代码就无法访问它。因此必须发布HDC以查看C#中的位图”